Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using statement vs. IDisposable.Dispose()

It has been my understanding that the using statement in .NET calls an IDisposable object's Dispose() method once the code exits the block.

Does the using statement do anything else? If not, it would seem that the following two code samples achieve the exact same thing:

Using Con as New Connection()     Con.Open()     'do whatever ' End Using  Dim Con as New Connection() Con.Open() 'do whatever ' Con.Dispose() 

I will give the best answer to whoever confirms that I am correct or points out that I am wrong and explains why. Keep in mind that I am aware that certain classes can do different things in their Dispose() methods. This question is about whether or not the using statement achieves the exact same result as calling an object's Dispose() method.

like image 829
oscilatingcretin Avatar asked Jun 11 '12 16:06

oscilatingcretin


People also ask

Does using statement Call Dispose?

The using statement guarantees that the object is disposed in the event an exception is thrown. It's the equivalent of calling dispose in a finally block.

What happens if you dont Dispose IDisposable?

IDisposable is usually used when a class has some expensive or unmanaged resources allocated which need to be released after their usage. Not disposing an object can lead to memory leaks.

When should you use IDisposable?

You should implement IDisposable when your class holds resources that you want to release when you are finished using them. Show activity on this post. When your class contains unmanaged objects, resources, opened files or database objects, you need to implement IDisposable .

How do you Dispose of IDisposable?

If you don't use using , then it's up to you (the calling code) to dispose of your object by explicitely calling Dispose().


1 Answers

using is basically the equivalent of:

try {   // code } finally {   obj.Dispose(); } 

So it also has the benefit of calling Dispose() even if an unhandled exception is thrown in the code within the block.

like image 164
Brian Warshaw Avatar answered Oct 12 '22 12:10

Brian Warshaw