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

后端 未结 29 2983
有刺的猬
有刺的猬 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:53

    The reason for the using statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.

    As in Understanding the 'using' statement in C# (codeproject) and Using objects that implement IDisposable (microsoft), the C# compiler converts

    using (MyResource myRes = new MyResource())
    {
        myRes.DoSomething();
    }
    

    to

    { // Limits scope of myRes
        MyResource myRes= new MyResource();
        try
        {
            myRes.DoSomething();
        }
        finally
        {
            // Check for a null resource.
            if (myRes != null)
                // Call the object's Dispose method.
                ((IDisposable)myRes).Dispose();
        }
    }
    

    C# 8 introduces a new syntax, named "using declarations":

    A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.

    So the equivalent code of above would be:

    using var myRes = new MyResource();
    myRes.DoSomething();
    

    And when control leaves the containing scope (usually a method, but it can also be a code block), myRes will be disposed.

提交回复
热议问题