I’ve read and I believe I understand what C#’s using statement does (please correct me if I’m wrong): Initializes an IDisposable object as read only to a limited scope (the using block). I know you can initialize before the using and that doesn’t limit the scope, but that is advised against here:
http://msdn.microsoft.com/en-us/library/yh598w02.aspx
I’m not always paying attention to what classes are subclasses of what. I’m not too sure what classes inherit from IDisposable. I’m not just curious what classes can be used in a using statement, but what classes would my coworkers expect to find in a using block? What classes should be in a using block? Also, is there really anything wrong with not using a using block and not calling Dispose? Is it just about memory or also stability?
Strictly speaking, any object that implements
IDisposableand whose scope is limited to that function should be within ausingblock. TheIDisposableinterface exists to allow classes that deal with unmanaged resources (database connections, file handles, window handles, etc.) to dispose of these resources in a timely, deterministic fashion.There are, in general, three ways in which an
IDisposableobject is used within a class:usingcan (and should) be used.Streamand needs to use it over the lifetime of the object. In this case, your class should implementIDisposableitself and dispose of the object(s) that you own when your ownDisposemethod is called. An example of this would be something likeSystem.IO.StreamWriterIDisposableobject’s usable lifetime is beyond the scope of a single method call, and may be beyond the lifetime of your object. In this case, someone else must be responsible for callingDispose.The first case is the most common that you’ll encounter, which is why the
usingblock exists. It takes care of ensuring that the object will be disposed of, even in the case of an exception.Some examples:
There’s no exhaustive list of classes that implement
IDisposable, as that list would be fairly large and filled with classes that you’ll likely never encounter. Think about what the class does; does it open some sort of connection or file that needs to be closed? In general, does it acquire some kind of resource that needs to be released? If so, it probably implements it. At a basic level, if the compiler allows you to enclose it inusing, then it implementsIDisposable.As to the consequences of not calling
Dispose, don’t consider it. Call Dispose. True, the defensive standard is that if your class uses unmanaged resources directly, then you should define a finalizer that will call dispose in the event that your object is collected and someone has failed to call it, but that should not be a design choice. Ever, as far as I’m aware.