User kokos answered the wonderful Hidden Features of C# question by mentioning the using
keyword. Can you elaborate on that? What are the uses of using
?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
The using keyword defines the scope for the object and then disposes of the object when the scope is complete. For example.
See here for the MSDN article on the C# using keyword.
For me the name "using" is a little bit confusing, because is can be a directive to import a Namespace or a statement (like the one discussed here) for error handling.
A different name for error handling would've been nice, and maybe a somehow more obvious one.
In conclusion, when you use a local variable of a type that implements
IDisposable
, always, without exception, useusing
1.If you use nonlocal
IDisposable
variables, then always implement theIDisposable
pattern.Two simple rules, no exception1. Preventing resource leaks otherwise is a real pain in the *ss.
1): The only exception is – when you're handling exceptions. It might then be less code to call
Dispose
explicitly in thefinally
block.The CLR converts your code into MSIL. And the using statement gets translated into a try and finally block. This is how the using statement is represented in IL. A using statement is translated into three parts: acquisition, usage, and disposal. The resource is first acquired, then the usage is enclosed in a try statement with a finally clause. The object then gets disposed in the finally clause.
using is used when you have a resource that you want disposed after it's been used.
For instance if you allocate a File resource and only need to use it in one section of code for a little reading or writing, using is helpful for disposing of the File resource as soon as your done.
The resource being used needs to implement IDisposable to work properly.
Example: