2

For example:

using (disposable object here)
{

}

What determines if I can use an object in this way?

Would this work correctly?

using (WebClient webClient = new WebClient())
{

}

4 Answers 4

7

In order to be used in a using statement, a class needs to implement the IDisposable interface.

In your example, WebClient derives from Component, which implements IDisposable, so it would indeed work.

Sign up to request clarification or add additional context in comments.

4 Comments

+1. An implicit conversion to IDisposable is also acceptable, as is an implicit dynamic conversion.
Not that it's useful, but using (null) {} works. I haven't bothered to find out why yet and not sure how I got into this bit of triviality.
@Kit, it works because the C# spec says: If a null resource is acquired, then no call to Dispose is made, and no exception is thrown.
Oh yeah. I forgot that. I guess my example is the canonical case to illustrate that!
1

You can use it if the class implements the IDisposable interface. This keyword is basically just syntactic sugar for calling the object's IDisposable.Dispose() method automatically after the using block.

The Dispose() method:

Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.

Comments

1

The object provided in the using statement must implement the IDisposable interface.

This interface provides the Dispose method, which should release the object's resources.

Reference: http://msdn.microsoft.com/en-us/library/yh598w02(v=vs.80).aspx

Comments

0

It works if the object implements IDisposable.

WebClient inherits from Component which does implement IDisposable so your code should work.

If it didn't work you should get a compile time error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.