Introduction
Type patterns help you check if a value is a certain type and use it right away. This makes your code simpler and clearer.
Type patterns help you check if a value is a certain type and use it right away. This makes your code simpler and clearer.
if (variable is TypeName variableName) { // use variableName here }
The is keyword checks the type and creates a new variable if it matches.
This new variable is only available inside the if-block.
obj is a string and use it as s inside the block.object obj = "hello"; if (obj is string s) { Console.WriteLine(s.ToUpper()); }
obj is an int and add 10 to it.object obj = 123; if (obj is int number) { Console.WriteLine(number + 10); }
object obj = 3.14; switch (obj) { case double d: Console.WriteLine($"Double: {d}"); break; case int i: Console.WriteLine($"Int: {i}"); break; default: Console.WriteLine("Unknown type"); break; }
This program checks each item in an array and prints its type and value using type patterns.
using System; class Program { static void Main() { object[] items = { "apple", 42, 3.14, null }; foreach (var item in items) { if (item is string text) { Console.WriteLine($"String: {text}"); } else if (item is int number) { Console.WriteLine($"Integer: {number}"); } else if (item is double dbl) { Console.WriteLine($"Double: {dbl}"); } else { Console.WriteLine("Unknown or null"); } } } }
Type patterns combine type checking and casting in one step.
They help avoid errors from wrong casts and make code easier to read.
Type patterns check and use a value's type in one step.
They simplify code by removing separate casts.
Useful in if statements and switch cases.
if statement like if (obj is string s)?is keyword with type patternis keyword checks if the object is of the specified type.s of that type.obj is a string and assigns it to s if true -> Option Cif statement in C#?if (variable is Type name).if (obj is Type var) [OK]object obj = 42;
if (obj is int number)
{
Console.WriteLine(number + 10);
}
else
{
Console.WriteLine("Not an int");
}
objobj holds the integer 42, so obj is int is true.if blocknumber is assigned 42, so number + 10 equals 52, which is printed.object obj = "hello";
if (obj is int number)
{
Console.WriteLine(number);
}
obj is a string, so obj is int number is false.if condition is false and no else block exists, nothing is printed.obj is not an int -> Option ADescribe(3.14)?double, which does not match int, string, or null._ matches any other type, so it returns "Unknown type".Pass the test and this pattern moves unknown