Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why do we put using before streamreader in c#

Tags:

c#

.net

using

why do we put using before streamreader in c#

using (StreamReader sr = new StreamReader("TestFile.txt")) 
{
    string line;
    // Read and display lines from the file until the end of 
    // the file is reached.
    while ((line = sr.ReadLine()) != null) 
    {
        Console.WriteLine(line);
    }
}
like image 329
colinfang Avatar asked Jul 12 '11 11:07

colinfang


1 Answers

using block in C# comes very handly while dealing with disposable objects. Disposable objects are those objects that can explicitly release the resources they use when called to dispose. As we know .Net garbage collection is non-deterministic so you can’t predict when exactly the object will be garbage collected.

Read this post for more in details : understanding ‘using’ block in C#

like image 79
Pranay Rana Avatar answered Oct 22 '22 04:10

Pranay Rana