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

Casting with as and is operators in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Casting Mastery in C#
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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");
Anull
Bnot null
CCompilation error
DRuntime exception
Attempts:
2 left
💡 Hint
The 'as' operator returns null if the cast fails instead of throwing an exception.
Predict Output
intermediate
2: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);
ARuntime exception
BTrue
CCompilation error
DFalse
Attempts:
2 left
💡 Hint
The 'is' operator checks if the object is compatible with the given type.
🔧 Debug
advanced
2: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;
AThe cast fails because 'obj' is a string, not an int, causing InvalidCastException.
BThe 'as' operator returns null, so 'num' is zero.
CThe code compiles but prints 'hello'.
DThe 'is' operator should be used instead of cast.
Attempts:
2 left
💡 Hint
Direct casting throws an exception if types are incompatible.
Predict Output
advanced
2: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");
ACompilation error
Bnull
C5
DRuntime exception
Attempts:
2 left
💡 Hint
Nullable types can be used with 'as' operator.
🧠 Conceptual
expert
2:00remaining
Difference between 'is' and 'as' operators
Which statement correctly describes the difference between 'is' and 'as' operators in C#?
A'is' throws exception on failure; 'as' returns default value.
B'is' performs casting and returns null if it fails; 'as' checks type and returns bool.
C'is' and 'as' are interchangeable and behave the same.
D'is' checks type compatibility and returns a bool; 'as' attempts cast and returns null if it fails.
Attempts:
2 left
💡 Hint
Think about what each operator returns when the cast is not possible.