Let’s start with a brief lesson on .NET. .NET, like most OO languages, needs the ability to perform “cleanup” when an object finally dies. One option for this is the Finalize method, which is called when the memory is freed, but since it’s the garbage collector’s job to do that freeing, you have no idea when (or even if) that will happen.

To solve that problem, .NET has an interface, IDisposable. The I, of course, is one of the lonely last relics of the tyranny that was “Hungarian Notation”. Classes which implement this interface have a Dispose method, which should be called by an instance’s owner to trigger cleanup (or can be auto-invoked through some nice syntactic sugar).

As an interesting, and odd quirk, classes may implement interfaces privately, so a disposable object might have a private Dispose method, that can only be invoked if you first cast to IDisposable.

There was a different problem .NET had, specifically, “wouldn’t it be nice to have a way to safely extend objects without inheriting?” Thus came “extension methods”. These are essentially static methods that simply take an object as its input and perform some operation on the object, but can be invoked as if they were class members.

For example:

    //declare this in a class somewhere, *any* class
    public static void SomeMethod(this SomeType) { /* do stuff */ }
    …
    SomeType i = new SomeType();
    i.SomeMethod() //does stuff
    //is equivalent to:
    SomeMethod(i)

“That’s some vaguely interesting trivia,” you might think to yourself, “but what on Earth do these two things have to do with each other?”

Well, Kaleb has a co-worker that had some issue with calling Dispose on every Disposable object. Maybe it was the fact that they’re sometimes implemented privately. Maybe some childhood trauma gave them an aversion to the word “dispose”. Perhaps they were just a wild and crazy guy. Maybe, and this is my theory, they thought they were far funnier than they were. Whatever problem they had, they solved it this way:

public static class IDisExt
{
        /// <summary>
        /// When Dispose just isn't enough. Let the object know how you really feel about it.
        /// </summary>
        /// <param name="i"></param>
        public static void DieYouGravySuckingPigDog(this IDisposable i)
        {
                i.Dispose();
        }
}
[Advertisement] Application Release Automation for DevOps – integrating with best of breed development tools. Free for teams with up to 5 users. Download and learn more today!