#941 – Checking to See If Objects Are Disposable

If a type implements the IDisposable interface, you should always call the Dispose method on an instance of the class when you are done using it.  The presence of IDisposable indicates that the class has some resources that can be released prior to garbage collection.

Below is one pattern for checking to see if an object implements the IDisposable interface.

            Dog bob = new Dog("Bob", 5);
            if (bob is IDisposable)

You can also use the using statement to automatically call Dispose on an object when you’re done using it.

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #941 – Checking to See If Objects Are Disposable

  1. Pingback: Dew Drop – September 30, 2013 (#1,634) | Morning Dew

  2. Pingback: Marina Shifrin Quit Featured In The Daily Six Pack: October 1, 2013

  3. Mark Nicholson says:

    This is ineffecient. A better way (to avoid the double cast) is to use the as keyword and check for null, e.g., var disposableBob = bob as IDisposable; if (disposableBob != null) disposableBob.Dispose();

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: