Rediģēt

Kopīgot, izmantojot


is operator (C# reference)

The is operator checks if the result of an expression is compatible with a given type. For information about the type-testing is operator, see the is operator section of the Type-testing and cast operators article. You can also use the is operator to match an expression against a pattern, as the following example shows:

static bool IsFirstFridayOfOctober(DateTime date) =>
    date is { Month: 10, Day: <=7, DayOfWeek: DayOfWeek.Friday };

In the preceding example, the is operator matches an expression against a property pattern with nested constant and relational patterns.

The is operator can be useful in the following scenarios:

  • To check the run-time type of an expression, as the following example shows:

    int i = 34;
    object iBoxed = i;
    int? jNullable = 42;
    if (iBoxed is int a && jNullable is int b)
    {
        Console.WriteLine(a + b);  // output 76
    }
    

    The preceding example shows the use of a declaration pattern.

  • To check for null, as the following example shows:

    if (input is null)
    {
        return;
    }
    

    When you match an expression against null, the compiler guarantees that no user-overloaded == or != operator is invoked.

  • You can use a negation pattern to do a non-null check, as the following example shows:

    if (result is not null)
    {
        Console.WriteLine(result.ToString());
    }
    
  • Beginning with C# 11, you can use list patterns to match elements of a list or array. The following code checks arrays for integer values in expected positions:

    int[] empty = [];
    int[] one = [1];
    int[] odd = [1, 3, 5];
    int[] even = [2, 4, 6];
    int[] fib = [1, 1, 2, 3, 5];
    
    Console.WriteLine(odd is [1, _, 2, ..]);   // false
    Console.WriteLine(fib is [1, _, 2, ..]);   // true
    Console.WriteLine(fib is [_, 1, 2, 3, ..]);     // true
    Console.WriteLine(fib is [.., 1, 2, 3, _ ]);     // true
    Console.WriteLine(even is [2, _, 6]);     // true
    Console.WriteLine(even is [2, .., 6]);    // true
    Console.WriteLine(odd is [.., 3, 5]); // true
    Console.WriteLine(even is [.., 3, 5]); // false
    Console.WriteLine(fib is [.., 3, 5]); // true
    

Note

For the complete list of patterns supported by the is operator, see Patterns.

C# language specification

For more information, see The is operator section of the C# language specification and Pattern matching.

See also