Coder Perfect

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

Problem

The using keyword was mentioned by user kokos in response to the fantastic Hidden Features of C# question. Could you expand on that? What are the benefits of utilizing?

Asked by ubermonkey

Solution #1

The using statement is used to ensure that the object is disposed of as soon as it is no longer in scope, and it does not require any explicit code to do so.

The C# compiler translates objects that implement IDisposable, as explained in Understanding the ‘using’ statement in C# (codeproject) and Using objects that implement IDisposable (microsoft).

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();
    }
}

The new “using declarations” syntax in C# 8 is as follows:

As a result, the equivalent code for the above would be:

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

MyRes will be discarded when control leaves the containing scope (typically a method, but it can also be a code block).

Answered by paulwhit

Solution #2

Because many people still do:

using (System.IO.StreamReader r = new System.IO.StreamReader(""))
using (System.IO.StreamReader r2 = new System.IO.StreamReader("")) {
   //code
}

I’m sure a lot of people are still unaware that you can:

using (System.IO.StreamReader r = new System.IO.StreamReader(""), r2 = new System.IO.StreamReader("")) {
   //code
}

Answered by BlackTigerX

Solution #3

Things like this:

using (var conn = new SqlConnection("connection string"))
{
   conn.Open();

    // Execute SQL statement here on the connection you created
}

This SqlConnection will be closed without the need to invoke the.Close() function manually, and even if an exception is thrown, without the requirement for a try/catch/finally block.

Answered by Joel Coehoorn

Solution #4

IDisposable can be accessed by using. It’s also possible to use it to alias types.

using (SqlConnection cnn = new SqlConnection()) { /* Code */}
using f1 = System.Windows.Forms.Form;

Answered by MagicKat

Solution #5

in the sense of utilizing

using (var foo = new Bar())
{
  Baz();
}

Is the abbreviation for a try/finally block. It’s the same as the code:

var foo = new Bar();
try
{
  Baz();
}
finally
{
  foo.Dispose();
}

You’ll notice that the first sample is far more concise than the second, and that even if an exception is thrown, there are a variety of things you would want to do as cleanup. As a result, we’ve created the Scope class, which allows you to execute arbitrary code in the Dispose function. So, if you had a property called IsWorking that you wanted to always set to false after performing an operation, you’d do it like this:

using (new Scope(() => IsWorking = false))
{
  IsWorking = true;
  MundaneYetDangerousWork();
}

More information on our answer and how we arrived at it may be found here.

Answered by Amanda Mitchell

Post is based on https://stackoverflow.com/questions/75401/what-are-the-uses-of-using-in-c