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:16

From MSDN:

C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.

The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.

In other words, the using statement tells .NET to release the object specified in the using block once it is no longer needed.

查看更多
低头抚发
3楼-- · 2018-12-31 04:18

The using statement is used to work with an object in C# that implements the IDisposable interface.

The IDisposable interface has one public method called Dispose that is used to dispose of the object. When we use the using statement, we don't need to explicitly dispose of the object in the code, the using statement takes care of it.

using (SqlConnection conn = new SqlConnection())
{

}

When we use the above block, internally the code is generated like this:

SqlConnection conn = new SqlConnection() 
try
{

}
finally
{
    // calls the dispose method of the conn object
}

For more details read: Understanding the 'using' statement in C#.

查看更多
查无此人
4楼-- · 2018-12-31 04:20

If the type implements IDisposable, it automatically disposes it.

Given:

public class SomeDisposableType : IDisposable
{
   ...implmentation details...
}

These are equivalent:

SomeDisposableType t = new SomeDisposableType();
try {
    OperateOnType(t);
}
finally {
    if (t != null) {
        ((IDisposable)t).Dispose();
    }
}

using (SomeDisposableType u = new SomeDisposableType()) {
    OperateOnType(u);
}

The second is easier to read and maintain.

查看更多
登录 后发表回答