Bird
Raised Fist0

Find the issue in this code:

medium📝 Debug Q7 of Q15
C Sharp (C#) - LINQ Fundamentals

Find the issue in this code:

var list = new List<string> { "apple", "banana" };
var result = list.FirstOrDefault(x => x.StartsWith("c"));
Console.WriteLine(result.Length);
AThrows NullReferenceException
BPrints 0
CPrints length of "apple"
DSyntax error in lambda
Step-by-Step Solution
Solution:
  1. Step 1: Understand FirstOrDefault() with predicate

    Returns first matching element or default (null for reference types) if none found.
  2. Step 2: Check if any string starts with "c"

    None do, so result is null.
  3. Step 3: Accessing Length on null causes exception

    Calling result.Length throws NullReferenceException.
  4. Final Answer:

    Throws NullReferenceException -> Option A
  5. Quick Check:

    Accessing property on null causes exception [OK]
Quick Trick: Check for null before accessing properties after FirstOrDefault() [OK]
Common Mistakes:
MISTAKES
  • Assuming FirstOrDefault() returns empty string instead of null
  • Not checking for null before property access
  • Confusing syntax error with runtime exception

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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