Bird
0
0

Given a list of objects, how can you safely print the length of all strings using 'as' and 'is' operators?

hard🚀 Application Q8 of 15
C Sharp (C#) - Polymorphism and Abstract Classes
Given a list of objects, how can you safely print the length of all strings using 'as' and 'is' operators?
List items = new() { "apple", 42, "banana", null };
foreach (var item in items)
{
    // Fill in here
}
AUse 'if (item is string s)' then print s.Length
BUse 'string s = item as string;' then check if s != null before printing s.Length
CDirectly cast with '(string)item' and print Length
DUse 'if (item.GetType() == typeof(string))' then cast and print Length
Step-by-Step Solution
Solution:
  1. Step 1: Compare 'as' and 'is' approaches for safe casting

    Both 'as' and 'is' can be used, but 'is' with pattern matching is concise and safe.
  2. Step 2: Evaluate options for safety and simplicity

    Use 'if (item is string s)' then print s.Length uses 'is' with variable declaration and null safety in one step, best practice here.
  3. Final Answer:

    Use 'if (item is string s)' then print s.Length -> Option A
  4. Quick Check:

    'is' pattern matching is safest and cleanest [OK]
Quick Trick: Use 'is Type var' to safely cast and use in one step [OK]
Common Mistakes:
MISTAKES
  • Using direct cast causing exceptions
  • Not checking null after 'as'
  • Using GetType() which fails on null

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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