Bird
Raised Fist0

Identify the error in this code snippet:

medium📝 Debug Q6 of Q15
C Sharp (C#) - Polymorphism and Abstract Classes
Identify the error in this code snippet:
object obj = new StringBuilder();
string s = obj as string;
if (s.Length > 0) Console.WriteLine(s);
AMissing cast to StringBuilder
BInvalid use of 'as' operator
CStringBuilder cannot be assigned to object
DPossible null reference exception on s.Length
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the 'as' cast result

    obj is a StringBuilder, not a string, so 'as string' returns null assigned to s.
  2. Step 2: Identify the error in accessing s.Length

    Since s is null, accessing s.Length causes a null reference exception at runtime.
  3. Final Answer:

    Possible null reference exception on s.Length -> Option D
  4. Quick Check:

    Accessing members on null after 'as' causes exceptions [OK]
Quick Trick: Always check for null after 'as' before member access [OK]
Common Mistakes:
MISTAKES
  • Ignoring null check after 'as'
  • Assuming 'as' throws exception
  • Confusing 'as' with direct cast

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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