top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

How using helps in Garbage collection in C#?

0 votes
35 views
How using helps in Garbage collection in C#?
posted May 17, 2017 by Pooja Bhanout

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Garbage collection in C# can be done through IDisposable interface. But another way of doing garbage collection is the use of using. this way we only have to think about the resource acquisition and the exception handling. the resource release will be done automatically because the resource acquisition is wrapped inside the using block.

TextReader tr2 = null;

//lets aquire the resources here                
try
{
    using (tr2 = new StreamReader(@"Files\test.txt"))
    {

        //do some operations using resources
        string s = tr2.ReadToEnd();

        Console.WriteLine(s);
    }
}
catch (Exception ex)
{
    //Handle the exception here
}

The resource release was done automatically. using block is the recommended way of doing such things as it will do the clean up even if the programmers forget to do it.

The use of 'using' block is possible because the TextReader class in the above example is implementing IDisposable
pattern

answer May 23, 2017 by Shweta Singh
Similar Questions
+1 vote

I am trying to get all the collection names from MongoDb server using C# code using db.GetCollectionNames() method.

I have 12 collections in my database, but the above method returns an empty list. I have verified that I am referring to the correct database. What am I doing wrong? Or if there is an alternate way?

Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...