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

Type checking patterns in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a type checking pattern in C#?
A type checking pattern is a way to test if an object is of a certain type and, if so, to extract it into a variable in a single step using the is keyword.
Click to reveal answer
beginner
How do you use the is keyword with a pattern to check type and assign a variable?
You write if (obj is TypeName variableName). This checks if obj is of type TypeName and if true, assigns it to variableName.
Click to reveal answer
intermediate
What is the benefit of using type checking patterns over traditional casting?
Type checking patterns combine the type check and variable assignment in one step, making code safer and cleaner by avoiding explicit casts and potential exceptions.
Click to reveal answer
intermediate
Explain the difference between is TypeName variable and as TypeName casting.
is TypeName variable checks type and assigns if true, while as TypeName tries to cast and returns null if it fails. The is pattern is safer and more concise.
Click to reveal answer
beginner
Show a simple example of type checking pattern in C#.
Example:<br>
object obj = "hello";<br>if (obj is string s)<br>{<br>    Console.WriteLine($"String length: {s.Length}");<br>}
Click to reveal answer
What does the C# expression if (obj is string s) do?
ACasts obj to string without checking
BChecks if obj is a string and assigns it to s if true
CAlways assigns obj to s regardless of type
DThrows an exception if obj is not a string
Which keyword is used in C# for type checking patterns?
Acast
Bas
Cis
Dtypeof
What happens if the type check fails in if (obj is int i)?
AThe if block is skipped and i is not assigned
BAn exception is thrown
Ci is assigned null
DThe program crashes
Which is safer to avoid exceptions when checking type and using the object?
AType checking pattern with 'is'
BDirect casting with (Type)
CUsing 'as' without null check
DIgnoring type and using object directly
What is the main advantage of type checking patterns?
AReplace all if statements
BMake code run faster
CAllow casting to any type without error
DCombine type check and assignment in one step
Explain how type checking patterns work in C# and why they are useful.
Think about how you check type and get the object ready to use in one step.
You got /5 concepts.
    Write a simple C# code snippet using a type checking pattern to check if an object is a string and print its length.
    Use 'if (obj is string s)' and then print s.Length.
    You got /5 concepts.