Please let other users know how useful this tip is by rating it below. Do you have a tip or code of your own you'd like to share? Submit it here.
Whenever you initialize an object in C#, you use dispose method to remove the object. You can avoid this by using keyword called 'using.'
This is what we used to write:
Object obj = new Object;
try
{
statement;
}
catch (exception e)
{
handle exceptions
}
finally
{
if (obj != null) ((IDisposable)obj).Dispose();
}
We can reduce these steps and write:
using (Object obj = new Object)
{
try
{
statement;
}
catch (exception e)
{
handle exceptions
}
}
You create an instance in a using statement to ensure that dispose is called on the object when the using statement is exited.