Concept Flow - Type patterns
Start with object variable
Check type with pattern
Cast and use
End
The program checks if an object matches a type pattern, then uses it if yes, otherwise skips or does other actions.
object obj = 42; if (obj is int number) { Console.WriteLine(number + 10); }
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Assign obj = 42 | obj holds 42 (int) | obj = 42 |
| 2 | Check if obj is int | obj is int? True | number = 42 |
| 3 | Execute inside if | Print number + 10 | Output: 52 |
| 4 | End | No more code | Program ends |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| obj | null | 42 (int) | 42 (int) | 42 (int) |
| number | undefined | undefined | 42 | 42 |
Type patterns check if an object matches a type.
Syntax: if (obj is Type varName) { use varName }
If true, varName holds the casted value.
If false, block is skipped.
Useful for safe type checks and casts.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