using Statement

The C# ECMA specification states that a using statement:

is exactly equivalent to:

This relies on the IDisposable interface from the System namespace:

Note that the cast inside the finally block implies that variable must be of a type that supports the IDisposable interface (either via inheritance or conversion operator). If it doesn’t you’ll get a compile time error.

Using on classes without IDisposable

It’s instructive to consider what would happen if class didn’t implement the IDisposable interface and you must implement Disposability in our own classes. One solution is the Object Adapter pattern. For example:

which you would use like this:

To make things a little easier you can create an implicit conversion operator:

which would allow you to write this: