Menu
Coddy logo textTech

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 string
  • ReadLine() — reads one line at a time, returns null when 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 icon

Challenge

Easy

Create a method named processFile that:

  1. Takes a filename as a string parameter
  2. Uses the using statement with a StreamReader to read all lines from the file
  3. Returns the number of lines in the file
  4. If a FileNotFoundException occurs, 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
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow