Reputation: 3485
using(YourType yourObject = new YourType())
{
//Treatment on you object
//Exception occurs here
}
when we write this way, the garbage collector automatically disposes the object, but is exceptions occurs inside this will the garbage collector still dispose the object or I have to write something for it, I know this is a lame q but m really confused, thnx
please explain the treatment in different .net frameworks to make things crystal clear.
Upvotes: 2
Views: 175
Reputation: 75316
From MSDN Documentation
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.
using (var object = new Object())
{
object.DoSomething();
}
equal with:
var object = new Object();
try
{
object.DoSomething();
}
finally
{
object.Dispose();
}
Upvotes: 1
Reputation: 82116
Yes, the using block will still call Dispose
on an exception. See MSDN documentation.
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object.
Also another useful article Avoiding Problems with the Using Statement.
Upvotes: 9