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

Casting with as and is operators in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the as operator do in C#?
The as operator tries to cast an object to a specified type. If it fails, it returns null instead of throwing an error.
Click to reveal answer
beginner
How does the is operator work in C#?
The is operator checks if an object is of a certain type and returns true or false.
Click to reveal answer
beginner
What happens if you use as to cast an incompatible type?
Instead of causing an error, as returns null when the cast is not possible.
Click to reveal answer
intermediate
Can is operator be used to safely cast an object?
No, is only checks the type and returns a boolean. To cast safely, combine is with a cast or use as.
Click to reveal answer
beginner
Show a simple example of using as and is operators.
Example:<br>
object obj = "hello";
string s1 = obj as string; // s1 = "hello"
if (obj is string s2) {
  // s2 is "hello"
}
Click to reveal answer
What does the as operator return if the cast fails?
Azero
Bthrows an exception
Cfalse
Dnull
Which operator checks if an object is a certain type and returns a boolean?
Ais
Bas
Ccast
Dtypeof
What is the result of obj as string if obj is an integer?
Anull
Binteger value
Cthrows exception
Dtrue
How can you safely cast an object after checking its type with is?
AUse <code>as</code> operator
BUse <code>typeof</code>
CUse explicit cast after <code>is</code> check
DUse <code>new</code> keyword
Which operator is better to avoid exceptions when casting?
Ais
Bas
Cexplicit cast
Dtypeof
Explain how the as and is operators help with type casting in C#.
Think about how to safely convert or check types without crashing your program.
You got /3 concepts.
    Describe a scenario where using as is better than an explicit cast.
    Consider when your program needs to keep running even if the cast is not possible.
    You got /3 concepts.