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?✗ Incorrect
The expression checks the type and assigns the variable only if obj is a string.
Which keyword is used in C# for type checking patterns?
✗ Incorrect
The 'is' keyword is used for type checking patterns in C#.
What happens if the type check fails in
if (obj is int i)?✗ Incorrect
If the type check fails, the if block does not run and the variable is not assigned.
Which is safer to avoid exceptions when checking type and using the object?
✗ Incorrect
'is' pattern safely checks type and assigns variable only if correct.
What is the main advantage of type checking patterns?
✗ Incorrect
They combine checking and assignment, making code cleaner and safer.
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.