Bird
Raised Fist0

Why does the as operator never throw an exception when casting fails, unlike a direct cast?

hard🧠 Conceptual Q10 of Q15
C Sharp (C#) - Polymorphism and Abstract Classes
Why does the as operator never throw an exception when casting fails, unlike a direct cast?
ABecause it only works with value types
BBecause it converts the object to a string automatically
CBecause it returns null instead of throwing an exception
DBecause it performs a compile-time check
Step-by-Step Solution
Solution:
  1. Step 1: Understand the behavior of 'as' operator

    The 'as' operator attempts to cast and returns null if it fails, avoiding exceptions.
  2. Step 2: Compare with direct cast behavior

    Direct cast throws InvalidCastException on failure, unlike 'as' which returns null.
  3. Final Answer:

    Because it returns null instead of throwing an exception -> Option C
  4. Quick Check:

    'as' returns null on failure, no exception [OK]
Quick Trick: 'as' returns null on failure, direct cast throws exception [OK]
Common Mistakes:
MISTAKES
  • Thinking 'as' converts types
  • Believing 'as' works only on value types
  • Confusing runtime and compile-time checks

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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