Bird
Raised Fist0

Identify the error in the following code snippet:

medium📝 Debug Q14 of Q15
C Sharp (C#) - File IO
Identify the error in the following code snippet:
StreamReader reader = new StreamReader("data.txt");
string line = reader.ReadLine();
Console.WriteLine(line);
reader.Close();
AMissing 'using' block to ensure file closure
BReadLine() should be ReadAll()
CStreamReader cannot read text files
Dreader.Close() should be called before ReadLine()
Step-by-Step Solution
Solution:
  1. Step 1: Check resource management

    The code opens a StreamReader but does not use a using block, risking resource leaks if exceptions occur.
  2. Step 2: Confirm method correctness

    ReadLine() is correct to read one line; Close() is called but manual closing is less safe than using.
  3. Final Answer:

    Missing 'using' block to ensure file closure -> Option A
  4. Quick Check:

    Use 'using' to auto-close files [OK]
Quick Trick: Always use 'using' to auto-close streams [OK]
Common Mistakes:
MISTAKES
  • Not using 'using' block for automatic disposal
  • Confusing ReadLine with ReadAll
  • Calling Close before reading

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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