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
using can be used to call IDisposable. It can also be used to alias types.
Just adding a little something that I was surprised did not come up. The most interesting feature of using (in my opinion) is that no mater how you exit the using block, it will always dispose the object. This includes returns and exceptions.
It doesn't matter if the exception is thrown or the list is returned. The DbContext object will always be disposed.
Another great use of using is when instantiating a modal dialog.
Another example of a reasonable use in which the object is immediately disposed:
Since a lot of people still do:
I guess a lot of people still don't know that you can do:
The using statement tells .NET to release the object specified in the using block once it is no longer needed. So you should use 'using' block for classes that require cleaning up after them, like System.IO Types.