开发者

What determines if I can use an object with the using function?

开发者 https://www.devze.com 2023-01-31 15:45 出处:网络
For example: using (disposable object here) { } What determines if 开发者_运维知识库I can use an object in this way?

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())
{

}


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.


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消