Search code examples
c#using-statement

Benefit/Use of using statement before streamwriter , streamreader


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());

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.