Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q5 of 15
C Sharp (C#) - Polymorphism and Abstract Classes
What will be the output of this code?
object val = 456;
string str = val as string;
Console.WriteLine(str == null ? "No string" : str);
ANo string
B456
CException thrown
Dnull
Step-by-Step Solution
Solution:
  1. Step 1: Use of as operator

    The as operator tries to cast val (which is an int boxed as object) to string. This cast fails and returns null.
  2. Step 2: Evaluate the conditional expression

    Since str is null, the ternary operator prints "No string".
  3. Final Answer:

    No string -> Option A
  4. Quick Check:

    Failed 'as' cast returns null, not exception [OK]
Quick Trick: Failed 'as' cast returns null, not exception [OK]
Common Mistakes:
MISTAKES
  • Expecting an exception on failed 'as' cast
  • Assuming implicit conversion to string
  • Printing 'null' string instead of custom message

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes