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?✗ Incorrect
The
as operator returns null if the cast is not possible, avoiding exceptions.Which operator checks if an object is a certain type and returns a boolean?
✗ Incorrect
The
is operator returns true or false depending on the object's type.What is the result of
obj as string if obj is an integer?✗ Incorrect
Casting an integer to string with
as returns null because the types are incompatible.How can you safely cast an object after checking its type with
is?✗ Incorrect
After confirming type with
is, you can safely cast using explicit cast syntax.Which operator is better to avoid exceptions when casting?
✗ Incorrect
The
as operator returns null instead of throwing exceptions, making it safer.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.