Basic concept of IDisposable
Any time you instantiate a class that Implements
IDisposable, you should call
.Dispose1 on that class when you have finished using it. This allows the class to clean up any managed or unmanaged dependencies that it may be using. Not doing this could cause a memory leak.
Using keyword ensures that
.Dispose is called, without you having to explicitly call it.
For example without
One major advantage
Using has is when an exception is thrown, because it ensures
.Dispose is called.
Consider the following. If an exception is thrown, you need to need to remember to call .Dispose but you might also have to check the state of the object to ensure you don't get a null reference error, etc.
A using block means you don't have to remember to do this and you can declare your object inside the
Declaring more objects in one Using
Sometimes, you have to create two
Disposable objects in a row. There is an easy way to avoid nesting
can be shortened into this one. The main advantage is that you gain one indentation level: