What are the uses of “using” in C#?

后端 未结 29 2971
有刺的猬
有刺的猬 2020-11-21 07:31

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

29条回答
  •  星月不相逢
    2020-11-21 08:01

    In conclusion, when you use a local variable of a type that implements IDisposable, always, without exception, use using1.

    If you use nonlocal IDisposable variables, then always implement the IDisposable 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 the finally block.

提交回复
热议问题