“Objects in System.Reflection are closer than they appear.”
by Greg McCoy

Posts Tagged ‘C#’

IDisposable Cheat Sheet

I was having a conversation with my boss a while back and he asked if we could discuss the using block a bit and any resonant patterns to its usage.

We discussed what it was, why, and how there should be some list out there indicating what is to be scoped with using() that may typically be forgotten.

Obviously, I can't dig into your proprietary code to show you your own IDisposables, and I'm not willing to list out every CLR IDisposable derived type. What I can do, however, is list what commonly used classes are IDisposable and why.

The What

I'm assuming by the fact that you're here, you know what IDisposable and the using block are. If not, here's a very brief overview.


IDisposable is the ever-impressive interface that informs your code that the type that it is applied to has explicit instruction on what is to happen in the case of its untimely demise.

Now, as .NET developers, most of us know this. In many cases, however, we haven't a clue as to what it really means, or why it matters. The reason for this is that, in the vast majority of cases, we are writing strictly managed code — managed code behaves differently than unmanaged code.

The using() Block

Wrapping up code that uses an IDisposable object is as elegant as can be. Simply do the following.

using (var mine = new MyClass())

After this block executes, the declared variable will invoke its Dispose() method, thereby running any needed finalization/disposal logic.

The Why

In managed code, the Garbage Collector is mostly self-sufficient and can usually handle getting rid of your pesky leftovers.

In unmanaged code, however, the GC is actually quite lost. It needs explicit knowledge of things that are beyond it's reflective capabilities… not beyond yours, though.

By indicating that a type is disposable, you gain the responsibility of adding a Dispose() method to your type that tells the CLR how to get rid of your unmanaged resources.

There are also classes that need to be disposed of in order to clean themselves up and out of a hierarchy. These types will essentially make whatever updates and notifications needed to other objects that may be using them, indicating that they are being disposed of, and won't be around for dessert.

The Classes

The following is by no means an exhaustive listing of the classes that implement IDisposable (nor a copy and paste of the Object Browser). This is hopefully a catalog of the most common disposable objects whose scope need to be explicitly defined.

Class Reason
Microsoft.ServiceModel.Channels.Mail.MailTransport Communication
System.Data.Common.DbCommand Communication
System.Data.Common.DbConnection Communication
System.Data.Common.DbDataReader Communication
System.Data.Common.DbTransaction Communication
System.Data.Linq.SqlClient.SqlProvider Communication
System.Data.OleDb.OleDbCommand Communication
System.Data.OleDb.OleDbConnection Communication
System.Data.SqlClient.SqlDataReader Communication
System.Diagnostics.Eventing.Reader.EventRecord Hardware (Memory)
System.Drawing.Brush Hardware (GDI)
System.Drawing.Font Hardware (GDI)
System.Drawing.Graphics Hardware (GDI)
System.Drawing.Image Hardware (GDI)
System.IO.BinaryReader File System
System.IO.BinaryWriter File System
System.IO.Stream File System
System.IO.StreamReader File System
System.IO.StreamWriter File System
System.IO.TextReader File System
System.IO.TextWriter File System
System.Net.FtpWebResponse Communication
System.Net.Mail.MailMessage Communication
System.Net.Sockets.TcpClient Communication
System.Net.Sockets.UdpClient Communication
System.Net.WebResponse Communication
System.Security.Cryptography.HashAlgorithm Hardware (Memory)
System.ServiceModel.ChannelFactory Communication
System.ServiceModel.Channels.Message Communication
System.ServiceModel.ClientBase Communication
System.Threading.Timer Hardware (CPU)
System.Web.UI.Control Notification
System.Windows.Forms.Control Hardware (GDI)
System.Xml.XmlReader File System
System.Xml.XmlWriter File System

Custom Classes

It is also very important to note that the use of these classes inside your own as members warrants implementing IDisposable on your own classes as well.

Having one or more disposable objects inside your class is, essentially, making your own class dependant on the resources (sockets, threads, the file system, etc...) that those objects need help cleaning up.

What else?

I will continue adding additional classes as they either become more common in my own use, or are requested. Not all developers write the same type of code, so this list obviously won't cover everything important by my hand alone. Please feel free to leave comments for others that I've left out and you think should be included.

Snippet: Compiler

Here’s a little snippet (from a friend; thanks again, man!) that will allow you, out of the box, to compile and execute C# code from your SOS input. The results of that code are returned as your response. I’m sure all of the C# coders out there can appreciate this one. One (pretty big) added bonus is the fact that this snippet compiler is not bound to C#. It’s not even bound to .NET! Within the configuration file, there are settings that will allow you to specify your own compiler, switches, and base code.

Click here to download the snippet: Compiler

Sample Input:
String text = "Hello World!";
foreach(Char c in text)
   String format = "[{0}:{1}] ";
   String character = c.ToString();
   String ascii = ((Int32)c).ToString();
   Console.Write(format, character, ascii.PadLeft(3, ‘0’));

Sample Output:
[H:072] [e:101] [l:108] [l:108] [o:111] [ :032] [W:087] [o:111] [r:114] [l:108] [d:100] [!:033]

Get a free book about code review best practices.