Smart Dispose method using Generics
Sample on how to create a Dispose function that will first check if the object is defined before attempting to dispose it.Passing the object to a method:
static public void SafeDispose(ref T objCleanUp) where T : IDisposable
{
if (objCleanUp != null)
{
objCleanUp.Dispose();
//objCleanUp = default(T); // actually, don't do this.
}
}
Use of an extension method:
static public void SafeDispose(this T objCleanUp) where T : IDisposable
{
if (objCleanUp != null)
{
objCleanUp.Dispose();
//objCleanUp = default(T); // actually, don't do this.
}
}
In both of these examples, setting the objCleanUp variable to NULL will not work. You'll get an error.
Setting it to 'default(T)' will work, however, it'll also create a new instance of the object. Not exactly what we're looking for here.
So, set the variable to NULL immediately after the call to SafeDispose().
Note: This method is obsolete. The '?' operator can be used instead:
objCleanup?.Dispose();
objCleanup = null;
The '?' operator will cause the Dispose() function call to not fail if 'objCleanup' is null.
Last modified by Mohit @ 4/4/2025 8:53:03 AM