Concept Flow - Type checking patterns
Start with object 'obj'
Check type with 'is' pattern
Cast and use
End
The program checks if an object matches a type pattern using 'is'. If yes, it casts and uses it; if no, it skips or handles differently.
object obj = "hello"; if (obj is string s) { Console.WriteLine(s.Length); }
| Step | Expression | Evaluation | Result | Action |
|---|---|---|---|---|
| 1 | obj = "hello" | Assign string to obj | obj = "hello" | Store string in obj |
| 2 | obj is string s | Check if obj is string | True | Cast obj to s |
| 3 | s.Length | Get length of s | 5 | Print 5 |
| 4 | End | No more code | - | Program ends |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| obj | null | "hello" | "hello" | "hello" | "hello" |
| s | undefined | undefined | "hello" | "hello" | "hello" |
Type checking patterns use 'is' to check and cast in one step.
Syntax: if (obj is Type varName) { use varName }
If true, varName is assigned and usable inside block.
If false, block is skipped.
This avoids separate casting and null checks.