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.
Jump into concepts and practice - no test required
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.if (obj is string s) do?is patternis keyword checks if an object is of a certain type.obj is a string, it assigns the value to s for use inside the block.is Type var checks type and assigns [OK]is Type var checks and assigns together [OK]obj is an int and assign it to number?is Type variable to check and assign.is int number, which is valid. Others use invalid keywords or syntax.is Type var syntax is correct [OK]is Type var for type check and assignment [OK]object obj = 42;
if (obj is int n)
{
Console.WriteLine(n + 10);
}
else
{
Console.WriteLine("Not an int");
}obj is int n is true and assigns 42 to n.n + 10 which is 42 + 10 = 52.object obj = "hello";
if (obj is int number)
{
Console.WriteLine(number);
}obj is int number is false and number is not assigned.List<object> items = new() { 1, "two", 3, null, 4.5 };, which code snippet correctly sums only the integer values using type checking patterns?if (item is int n) to add only integers. int sum = 0;
foreach (int n in items)
{
sum += n;
}
Console.WriteLine(sum); tries to cast all items to int in foreach, causing error. int sum = 0;
foreach (var item in items)
{
if (item is double d) sum += (int)d;
}
Console.WriteLine(sum); sums doubles cast to int, which is incorrect. int sum = 0;
foreach (var item in items)
{
sum += (int)item;
}
Console.WriteLine(sum); casts all items to int without checking, causing runtime errors.is int var to filter integers safely [OK]if (item is int n) to sum integers safely [OK]