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