Bird
Raised Fist0

Identify the error in this code snippet:

medium📝 Debug Q14 of Q15
C Sharp (C#) - Polymorphism and Abstract Classes
Identify the error in this code snippet:
object obj = 123;
string s = obj as string;
Console.WriteLine(s.Length);
AThe <code>is</code> operator is used incorrectly.
BThe <code>as</code> cast will fail and <code>s</code> will be null, causing a null reference exception.
CYou cannot use <code>as</code> with value types like int.
DThe code will compile but print 3.
Step-by-Step Solution
Solution:
  1. Step 1: Understand as cast with incompatible types

    Since obj holds an int (123), casting it as string returns null.
  2. Step 2: Analyze the usage

    Since s is null, calling s.Length causes a null reference exception.
  3. Final Answer:

    The as cast will fail and s will be null, causing a null reference exception. -> Option B
  4. Quick Check:

    as returns null on failure; check before use [OK]
Quick Trick: Always check for null after as cast before use [OK]
Common Mistakes:
MISTAKES
  • Assuming is fixes null issues
  • Not checking s for null before accessing members
  • Thinking as works with value types

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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