How to Use is Pattern in C# for Type Checking and Matching
In C#, the
is pattern lets you check an object's type and, if it matches, assign it to a new variable in one step using syntax like if (obj is Type varName). This simplifies type checks and avoids extra casting.Syntax
The is pattern syntax combines type checking and variable assignment. It looks like this:
expr is Type varName: Checks ifexpris ofType. If yes, assigns it tovarName.expr is null: Checks ifexpris null.expr is not Type: Checks ifexpris NOT ofType.
This pattern helps write concise and safe code without explicit casts.
csharp
if (obj is string s) { Console.WriteLine($"String value: {s}"); }
Example
This example shows how to use the is pattern to check an object's type and use it safely:
csharp
using System; class Program { static void Main() { object obj = "Hello, world!"; if (obj is string text) { Console.WriteLine($"The string is: {text}"); } else { Console.WriteLine("obj is not a string."); } obj = 123; if (obj is int number) { Console.WriteLine($"The number is: {number}"); } else { Console.WriteLine("obj is not an int."); } } }
Output
The string is: Hello, world!
The number is: 123
Common Pitfalls
Common mistakes when using is pattern include:
- Trying to use the variable outside the
ifblock where it is declared. - Using
iswithout a variable when you need the value. - Confusing
ispattern with equality checks.
Always remember the variable declared with is is only available inside the block where the pattern matches.
csharp
object obj = "text"; // Wrong: variable 's' not declared outside if // Console.WriteLine(s); // Error if (obj is string s) { Console.WriteLine(s); // Correct usage }
Quick Reference
Summary tips for using is pattern:
- Use
expr is Type varNameto check type and get variable. - Use
is notto check for non-matching types. - Variable scope is limited to the block where pattern matches.
- Works with nullable and reference types.
Key Takeaways
Use
is Type varName to check type and assign in one step.The variable declared with
is is only available inside the matching block.Avoid casting after
is by using pattern matching.Use
is not Type to check for types that do not match.The
is pattern improves code safety and readability.