What are the uses of “using” in C#

Technology CommunityCategory: C#What are the uses of “using” in C#
VietMX Staff asked 3 years ago

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

The .NET CLR 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();
    }
}