Information Technology Reference
In-Depth Information
finally
{
myConnection.Dispose();
}
If you use the using statement with a variable of a type that does not sup-
port the IDisposable interface, the C# compiler generates an error. For
example:
// Does not compile:
// String is sealed, and does not support IDisposable.
using ( string msg = "This is a message" )
Console .WriteLine(msg);
The using statement works only if the compile-time type supports the
IDisposable interface. You cannot use it with arbitrary objects:
// Does not compile.
// Object does not support IDisposable.
using ( object obj = Factory .CreateResource())
Console .WriteLine(obj.ToString());
A quick defensive as clause is all you need to safely dispose of objects that
might or might not implement IDisposable:
// The correct fix.
// Object may or may not support IDisposable.
object obj = Factory .CreateResource();
using (obj as IDisposable )
Console .WriteLine(obj.ToString());
If obj implements IDisposable , the using statement generates the
cleanup code. If not, the using statement degenerates to using(null) ,
which is safe but doesn't do anything. If you're not sure whether you
should wrap an object in a using block, err on the side of safety: Assume
that it does and wrap it in the using clause shown earlier.
That covers the simple case: Whenever you use one disposable object that
is local to a method, wrap that one object in a using statement. Now you
can look at a few more complicated usages. Two different objects need to
be disposed in that first example: the connection and the command. My
example creates two different using statements, one wrapping each of
the two objects that need to be disposed. Each using statement gener-
 
Search WWH ::




Custom Search