Benefit/Use of using statement before streamwriter , streamreader [duplicate]

走远了吗. 提交于 2019-12-02 01:19:46

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!