Using .Net. No, I am not referring to drug that I am using called .NET, but the Using statement in the .NET framework. The “Using” statement in .NET framework provides a convenient syntax that ensures the correct use of IDisposable objects.
If .NET object you are using implements IDisposable, then you can simply call the Dispose method your self
But what if an exception happens when you are doing something with the report? The .Close and .Dispose methods will never be called.
Or you could also use a Try Catch block, and in the catch perform the .Close and .Dispose
But this does become verbose and it requires you to remember the try/catch and add the close and/or dispose methods.
Now, with the Using statement, it looks like this.
This Using block, will instantiate the report object, and when you are done doing something with that report object, it will properly dispose of the object, and IF the object has a .close method, the Dispose method will perform the Close and then Dispose. Now… depending on your object and what you are doing with the “do something here”, you may still want to put this Using inside a Try/Catch.
You can also nest Using statements. Below is an example of this, and putting it all in a Try/Catch block.
In VB.Net it is a bit more verbose, but it all works the same. Below is an example in VB.Net, with out the Try/Catch.