Glossary / is patterns

is patterns

The is operator evaluates whether a value matches a type or pattern, returning a Boolean and optionally binding variables. Modern C# is patterns combine runtime type checks with constant, relational, property, list, and logical matching, and their successful branches inform nullable and definite-assignment analysis.

Common forms

if (input is string { Length: > 0 } text)
    Console.WriteLine(text);

if (count is > 0 and <= 100)
    Process(count);

x is T name tests the runtime type and declares a variable in the true branch. x is null is preferable to x == null when overloaded equality could change behavior. is not null expresses a non-null check. Pattern variables have flow-sensitive scopes and are definitely assigned only where the pattern is known to match.

The is operator does not perform arbitrary conversions: a numeric value does not match another numeric type simply because conversion is possible. For conversion, use casts, TryParse, or Convert as appropriate. Pattern properties can execute getters and nested patterns can throw if getters do.

Interview questions

  1. How is is T x useful? It combines a runtime type check with a safely scoped variable binding.
  2. Why use is null? It avoids overloaded == semantics and tests null directly.
  3. Does is perform numeric conversion? No, it checks type/pattern compatibility rather than arbitrary conversion.
  4. When is a pattern variable definitely assigned? In control-flow regions where the compiler knows the pattern succeeded.
  5. Can property pattern evaluation have effects? Yes, getters may run and may throw.

References