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

后端 未结 29 2733
有刺的猬
有刺的猬 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.

    0 讨论(0)
  • 2020-11-21 08:03

    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.

    0 讨论(0)
  • 2020-11-21 08:04

    The using statement provides a convenience mechanism to correctly use IDisposable objects. As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.

    This comes from: here

    0 讨论(0)
  • 2020-11-21 08:05

    When using ADO.NET you can use the keywork for things like your connection object or reader object. That way when the code block completes it will automatically dispose of your connection.

    0 讨论(0)
  • 2020-11-21 08:05

    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.

    0 讨论(0)
提交回复
热议问题