Using vs. Try-Finally
Part of the Logic & Flow section of Coddy's C# journey — lesson 28 of 66.
Both using statements and try-finally blocks help manage resources that need to be properly disposed of. The using statement provides a cleaner, more concise way to ensure that IDisposable objects are properly cleaned up.
Note: using replaces the try-finally pattern for disposal — it does not replace try-catch. You can still wrap a using block inside a try-catch to handle exceptions.
Let's look at a try-finally approach first:
StreamReader reader = null;
try
{
reader = new StreamReader("file.txt");
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
finally
{
if (reader != null)
{
reader.Dispose();
}
}
The using statement simplifies this code:
using (StreamReader reader = new StreamReader("file.txt"))
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
The using statement automatically calls Dispose() when the block exits, even if an exception occurs.
What is StreamReader?StreamReader is a class used to read text from files. You create one by passing a filename, and it opens the file for reading. It implements IDisposable, so it must be properly closed after use — which is exactly what using handles for you.
Common StreamReader methods:
ReadToEnd()— reads the entire file as a single stringReadLine()— reads one line at a time, returnsnullwhen the end of the file is reached
To count lines in a file, you can use a ReadLine() loop:
using (StreamReader reader = new StreamReader("file.txt"))
{
int lineCount = 0;
while (reader.ReadLine() != null)
{
lineCount++;
}
Console.WriteLine(lineCount);
}
You can also combine using with try-catch to handle exceptions like a missing file:
try
{
using (StreamReader reader = new StreamReader("file.txt"))
{
int lineCount = 0;
while (reader.ReadLine() != null)
{
lineCount++;
}
Console.WriteLine(lineCount);
}
}
catch (FileNotFoundException)
{
Console.WriteLine("File not found");
}
Challenge
EasyCreate a method named processFile that:
- Takes a filename as a string parameter
- Uses the
usingstatement with aStreamReaderto read all lines from the file - Returns the number of lines in the file
- If a
FileNotFoundExceptionoccurs, print "File not found" and return -1
Try it yourself
using System;
using System.IO;
class ProcessFile
{
public static int processFile(string filename)
{
// Write your code here
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety