Question

Possible Duplicate:
What is the C# Using block and why should I use it?

So I've just noticed that at msdn examples and some stackoverflow questions there were answer where the using statement is used before the streamwriter etc, but what is actually the benefit? Since I've never been taught/told/read any reason to use it.

            using (StreamReader sr = new StreamReader(path)) 
            {
                while (sr.Peek() >= 0) 
                    Console.WriteLine(sr.ReadLine());
            }

Instead of:

            StreamReader sr = new StreamReader(path);
            while (sr.Peek() >= 0) 
                Console.WriteLine(sr.ReadLine());
Was it helpful?

Solution

The using block calls the Dispose method of the object used automatically, and the good point is that it is guaranteed to be called. So the object is disposed regardless of the fact an exception is thrown in the block of statements or not. It is compiled into:

{
    StreamReader sr = new StreamReader(path);
    try
    {
        while (sr.Peek() >= 0) 
            Console.WriteLine(sr.ReadLine());
    }
    finally
    {
        if(sr != null)
            sr.Dispose();
    }
}

The extra curly braces are put to limit the scope of sr, so that it is not accessible from outside of the using block.

OTHER TIPS

The using provides a convenient syntax that ensures the correct use of IDisposable objects. It is compiled into:

StreamReader sr = new StreamReader(path);
try 
{
    while (sr.Peek() >= 0) 
        Console.WriteLine(sr.ReadLine());
} finally
{
    sr.Dispose();
}

As documented on MSDN

using statement works on stuff that implement IDisposable interface.

.net will garantee that the StreamReader will be disposed.

You don't have to worry about closing or managing it further: just use what you need inside the "using" scope.

It automatically calls the StreamReader.Dispose() method for you. If you choose not to use the using keyword, you end up with an open stream after you run your code block. This is beneficial if you want to reserve a file (etc) for continued use, but could be bad practice if you do are not going to manually dispose of it when finished.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top