Challenge - 5 Problems
Casting Mastery in C#
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of casting with 'as' operator
What is the output of this C# code snippet?
C Sharp (C#)
class Animal {} class Dog : Animal {} Animal a = new Animal(); Dog d = a as Dog; Console.WriteLine(d == null ? "null" : "not null");
Attempts:
2 left
💡 Hint
The 'as' operator returns null if the cast fails instead of throwing an exception.
✗ Incorrect
The variable 'a' is an Animal instance, not a Dog. Using 'as' to cast to Dog returns null because 'a' is not a Dog or derived from Dog.
❓ Predict Output
intermediate2:00remaining
Using 'is' operator with inheritance
What will this C# code print?
C Sharp (C#)
class Vehicle {} class Car : Vehicle {} Vehicle v = new Car(); Console.WriteLine(v is Car);
Attempts:
2 left
💡 Hint
The 'is' operator checks if the object is compatible with the given type.
✗ Incorrect
The variable 'v' refers to a Car instance, so 'v is Car' returns true.
🔧 Debug
advanced2:00remaining
Why does this cast cause a runtime error?
Consider this code snippet. Which option explains why it throws an exception?
C Sharp (C#)
object obj = "hello"; int num = (int)obj;
Attempts:
2 left
💡 Hint
Direct casting throws an exception if types are incompatible.
✗ Incorrect
Casting a string object to int directly causes InvalidCastException at runtime.
❓ Predict Output
advanced2:00remaining
Result of 'as' operator with value types
What happens when you run this C# code?
C Sharp (C#)
object o = 5; int? n = o as int?; Console.WriteLine(n.HasValue ? n.Value.ToString() : "null");
Attempts:
2 left
💡 Hint
Nullable types can be used with 'as' operator.
✗ Incorrect
The 'as' operator can cast boxed value types to nullable types, so 'n' has value 5.
🧠 Conceptual
expert2:00remaining
Difference between 'is' and 'as' operators
Which statement correctly describes the difference between 'is' and 'as' operators in C#?
Attempts:
2 left
💡 Hint
Think about what each operator returns when the cast is not possible.
✗ Incorrect
'is' returns true or false depending on type compatibility; 'as' returns the casted object or null if cast fails.