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.