Bird
Raised Fist0

What is the output of the following code?

medium📝 Predict Output Q13 of Q15
C Sharp (C#) - Polymorphism and Abstract Classes
What is the output of the following code?
object obj = "hello";
string s = obj as string;
Console.WriteLine(s != null ? s.ToUpper() : "null");
AHELLO
Bnull
Chello
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the as cast

    The object obj holds a string "hello". Using as string casts it successfully, so s is "hello".
  2. Step 2: Evaluate the conditional output

    Since s is not null, s.ToUpper() is called, producing "HELLO".
  3. Final Answer:

    HELLO -> Option A
  4. Quick Check:

    as cast success means uppercase output [OK]
Quick Trick: If as cast succeeds, use the object; else null [OK]
Common Mistakes:
MISTAKES
  • Assuming as throws exception on failure
  • Forgetting to check for null after as
  • Confusing output case sensitivity

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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