Alex Rivera | Logout

Expected behavior of `using` statement on type not implementing `IDispoable`?

Asked 2009-04-01T21:28:48.363
13

Will the following code work if resource doesn't implement IDisposable?

T resource = new T();
using (resource as IDisposable)
{
  ...
}
Edit
Report

2 Answers

17

Yes. A using statement checks whether it's being given null and avoids trying to call Dispose if so.

From section 8.13 of the C# 3 spec:

A using statement is translated into three parts: acquisition, usage, and disposal. Usage of the resource is implicitly enclosed in a try statement that includes a finally clause. This finally clause disposes of the resource. If a null resource is acquired, then no call to Dispose is made, and no exception is thrown.

answered 2009-04-01T21:33:56.043
1

It can be useful when the type explicitly implements IDisposable in which case the Dispose method is not directly accessible on the type unless the type is casted to an IDisposable, Using the 'as' does a safe cast and ensures that Dispose is called. In most cases when the type explicitly implements IDisposable, it provides methods such as 'Close' which in turn calls Dispose

answered 2009-04-02T07:36:04.957

Your Answer