The 'using' statement in .Net 2.0

The 'using' statement in .Net 2.0 is to dispose an object implicitly when the code block is finished. The compiler translates 'using' statement to try...finally statement and call the object's dispose() function.

Suppose that we have this using statement:

using (obj)
{
obj.DoSomething();
}
From concept, the compiler translates that block into code like below:

try
{
obj.DoSomething();
}
finally
{
if (obj != null)
{
obj.Dispose();
}
}

But when obj is not an IDisposable object, that using statement can not be compiled. For example, ITestInterface has one method DoSomething(). TestClass is an implementation class for ITestInterface and IDisposable, the code below can not be compiled:

public class Program
{
static void Main(string [] args)
{
ITestInterface obj = new TestClass();
using (obj)
{
obj.DoSomething();
}
}
}

To make it work, we should add "as IDisposable":

using (obj as IDisposable)
{
obj.DoSomething();
}

The logic is same as:

using (IDisposable obj2 = (obj as IDisposable))
{
obj.DoSomething();
}

0 comments: