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

后端 未结 29 3049
有刺的猬
有刺的猬 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 07:50

    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:

    using (File file = new File (parameters))
    {
        *code to do stuff with the file*
    }
    

提交回复
热议问题