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.
Beginning with C# 7.0, 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.Beginning with C# 9.0, 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()); }
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 the following C# language proposals: