IDisposable Part 5 – Using IDisposable Classes in C#
For part 5 of my series on IDisposable, I want to focus on using IDisposable objects. We’ve seen many of the ways and reasons you might create an IDisposable class. Now, we’ll use the classes we’ve created.
When we plan to use a class that implements IDisposable, there is a nice feature in C# of which we can take advantage: the using statement.
As an example, let’s suppose we want to use our LoggingLicenseAGenerator class from Part 2. We would use this as follows:
string user = "Reed"; // Initialize and use our license generator using (var licenseGen = new LoggingLicenseAGenerator()) { bool granted = licenseGen.LicenseValid(user); }
The nice thing here is that you’re guaranteed to dispose of licenseGen automatically, even if an exception is thrown and unhandled. (For details of how the compiler interprets “usingâ€, see the MSDN reference page, under Remarks.)
This follows the basic premise of RAII. You acquire your license generator (resource) in a way that it will be cleaned up automatically as it goes out of scope.
If you need to save the IDisposable class for use throughout an object’s lifetime, or across multiple scopes, it’s a good idea to make your class IDisposable itself, encapsulating your IDisposable class. Again, we want to always guarantee that an IDisposable object will get disposed as soon as we finish with it.
That being said, if we forget to do this, and we wrote our classes correctly, there shouldn’t be horrible consequences. As soon as our IDisposable object goes out of scope, it will be a candidate for garbage collection. At some point, the GC should collect this object. If the object directly uses native resources, it will have a finalizer that gets called (see Part 1 for details), and disposes of the resources at this point.
hi,
First of all. Thanks very much for your useful post.
I just came across your blog and wanted to drop you a note telling you how impressed I
was with the information you have posted here.
Please let me introduce you some info related to this post and I hope that it is useful
for .Net community.
There is a good C# resource site, Have alook
http://www.csharptalk.com/2009/09/c-class.html
http://www.csharptalk.com
simi