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

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

Choose your learning style9 modes available
Recall & Review
beginner
What is a type pattern in C#?
A type pattern checks if an object is of a specific type and, if so, allows you to use it as that type in a safe way.
Click to reveal answer
beginner
How do you use a type pattern with the is keyword?
You write if (obj is TypeName variableName). This checks if obj is of TypeName and, if true, assigns it to variableName for use inside the block.
Click to reveal answer
beginner
What happens if the type pattern check fails?
If the object is not of the specified type, the pattern check returns false and the variable is not assigned.
Click to reveal answer
intermediate
Can you use type patterns in a switch statement?
Yes! You can match the type of a variable in switch cases using type patterns, making code clearer and safer.
Click to reveal answer
beginner
Example: What does this code do?<br>
if (obj is string s) { Console.WriteLine(s.Length); }
It checks if obj is a string. If yes, it assigns it to s and prints the length of the string.
Click to reveal answer
What does the type pattern if (obj is int number) do?
AChecks if obj is an int and assigns it to number if true
BConverts obj to int without checking
CAlways assigns obj to number
DChecks if obj is null
Which keyword is used with type patterns to check an object's type?
Ais
Btypeof
Cswitch
Das
What happens if the type pattern check fails?
AThe variable is assigned default value
BThe code throws an exception
CThe variable is assigned null
DThe condition is false and variable is not assigned
Can type patterns be used inside a switch statement?
ANo, only if statements
BYes, to match types in cases
COnly with enums
DOnly with strings
What is the benefit of using type patterns?
AThey automatically convert types
BThey replace all casts
CThey allow safe type checking and variable assignment
DThey improve performance by skipping checks
Explain how type patterns work with the 'is' keyword in C#.
Think about how you check and use an object's type in one step.
You got /3 concepts.
    Describe how type patterns can be used in a switch statement and why that is useful.
    Consider how switch can handle different types safely.
    You got /3 concepts.