Bird
0
0

How can you safely extract a string from an object and convert it to uppercase using pattern matching?

hard🚀 Application Q9 of 15
C Sharp (C#) - Polymorphism and Abstract Classes
How can you safely extract a string from an object and convert it to uppercase using pattern matching?
Avar upper = ((string)obj).ToUpper();
Bif (obj is string s) { var upper = s.ToUpper(); }
Cif (obj as string s) { var upper = s.ToUpper(); }
Dvar upper = obj.ToString().ToUpper();
Step-by-Step Solution
Solution:
  1. Step 1: Use pattern matching to check and assign

    if (obj is string s) safely checks type and assigns s.
  2. Step 2: Call ToUpper() on s

    This avoids exceptions if obj is not a string.
  3. Final Answer:

    if (obj is string s) { var upper = s.ToUpper(); } -> Option B
  4. Quick Check:

    Safe extraction and use = B [OK]
Quick Trick: Use 'is string s' to avoid invalid cast exceptions [OK]
Common Mistakes:
MISTAKES
  • Using 'as' incorrectly with variable declaration
  • Casting without checking type first

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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