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.
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.
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.
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 .
If you don't use using , then it's up to you (the calling code) to dispose of your object by explicitely calling Dispose().
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With