0
0
C Sharp (C#)programming~10 mins

Type checking patterns in C Sharp (C#) - Step-by-Step Execution

Choose your learning style9 modes available
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.
Execution Sample
C Sharp (C#)
object obj = "hello";
if (obj is string s)
{
    Console.WriteLine(s.Length);
}
Checks if obj is a string, then prints its length.
Execution Table
StepExpressionEvaluationResultAction
1obj = "hello"Assign string to objobj = "hello"Store string in obj
2obj is string sCheck if obj is stringTrueCast obj to s
3s.LengthGet length of s5Print 5
4EndNo more code-Program ends
💡 After printing length, program ends.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
objnull"hello""hello""hello""hello"
sundefinedundefined"hello""hello""hello"
Key Moments - 2 Insights
Why can we use 's' inside the if block without explicit casting?
Because the 'is' pattern both checks type and casts obj to s if true, as shown in step 2 of the execution_table.
What happens if obj is not a string?
The condition in step 2 would be false, so the code inside the if block would not run, skipping the cast and print.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2, what is the result of 'obj is string s'?
AFalse
BTrue
CThrows error
DUndefined
💡 Hint
Check the 'Result' column in step 2 of execution_table.
At which step is the variable 's' assigned a value?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at variable_tracker and execution_table step 2 where casting happens.
If obj was an int instead of a string, what would happen at step 2?
AResult would be True and s assigned
BProgram would crash
CResult would be False and s undefined
Ds would be null
💡 Hint
Refer to key_moments about what happens if obj is not a string.
Concept Snapshot
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.
Full Transcript
This example shows how C# uses type checking patterns with the 'is' keyword. We start with an object 'obj' assigned a string "hello". Then we check if 'obj' is a string and simultaneously cast it to variable 's'. Since obj is a string, the condition is true, and 's' holds the string value. We then print the length of 's', which is 5. If obj was not a string, the if block would be skipped. This pattern helps safely check and use types without extra casting code.