What is the C# Using block and why should I use it

2018-12-31 03:44发布

This question already has an answer here:

What is the purpose of the Using block in C#? How is it different from a local variable?

9条回答
素衣白纱
2楼-- · 2018-12-31 04:00

Using calls Dispose() after the using-block is left, even if the code throws an exception.

So you usually use using for classes that require cleaning up after them, like IO.

So, this using block:

using (MyClass mine = new MyClass())
{
  mine.Action();
}

would do the same as:

MyClass mine = new MyClass();
try
{
  mine.Action();
}
finally
{
  if (mine != null)
    mine.Dispose();
}

Using using is way shorter and easier to read.

查看更多
步步皆殇っ
3楼-- · 2018-12-31 04:01

It is really just some syntatic sugar that does not require you to explicity call Dispose on members that implement IDisposable.

查看更多
与风俱净
4楼-- · 2018-12-31 04:02

Placing code in a using block ensures that the objects are disposed (though not necessarily collected) as soon as control leaves the block.

查看更多
孤独总比滥情好
5楼-- · 2018-12-31 04:02
using (B a = new B())
{
   DoSomethingWith(a);
}

is equivalent to

B a = new B();
try
{
  DoSomethingWith(a);
}
finally
{
   ((IDisposable)a).Dispose();
}
查看更多
何处买醉
6楼-- · 2018-12-31 04:02

The using statement obtains one or more resources, executes a statement, and then disposes of the resource.

查看更多
千与千寻千般痛.
7楼-- · 2018-12-31 04:15

Also take note that the object instantiated via using is read-only within the using block. Refer to the official C# reference here.

查看更多
登录 后发表回答