Bird
0
0

Identify the error in this C# code snippet using List<string>:

medium📝 Debug Q14 of 15
C Sharp (C#) - Collections
Identify the error in this C# code snippet using List<string>:
List colors = new List();
colors.Add("red");
colors[1] = "blue";
Console.WriteLine(colors[1]);
AIndexOutOfRangeException because index 1 does not exist yet.
BSyntax error in Add method usage.
CCannot assign string to List<string> element.
DNo error; code runs and prints 'blue'.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze list content after Add

    After colors.Add("red"), list has one element at index 0 only.
  2. Step 2: Check assignment to colors[1]

    colors[1] does not exist yet, so assigning to it causes IndexOutOfRangeException.
  3. Final Answer:

    IndexOutOfRangeException because index 1 does not exist yet. -> Option A
  4. Quick Check:

    Assigning to non-existing index throws exception [OK]
Quick Trick: List index must exist before assignment; use Add to add items [OK]
Common Mistakes:
MISTAKES
  • Trying to assign to index without adding
  • Confusing Add and index assignment
  • Expecting automatic list expansion

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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