Suppose that we have this using statement:
From concept, the compiler translates that block into code like below:
using (obj)
{
obj.DoSomething();
}
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:
Post a Comment