Explain using statement in C# code in middle of code… (not in header as loading libraries)

Issue

Please, can anyone explain to me statement in c# “using”. I know that I use it at header of program to load basic libraries such as using System.Text;. But is not clear to me, What is the difference between:

using (var font1 = new Font("Arial", 10.0f)) 
{
    byte charset = font1.GdiCharSet;
}

and:

using var font1 = new Font("Arial", 10.0f);
byte charset = font1.GdiCharSet;

And Yes, I read the manuals for C#, But i donĀ“t understand this in practical way.

Solution

using is used in conjunction with types that implement the IDisposable interface.

It ensures that when the object is out of scope, the Dispose method is called (as defined in IDisposable) and is often used to dispose of unmanaged resources.

Your first example is a traditional using block, where the object scope is defined by the following {}.

Your second is a new using statement, introduced in C#8, where the scope is the enclosing block, as with other local variables.

It is roughly equivalent to:

var font1 = new Font("Arial", 10.0f);
byte charset = font1.GdiCharSet;
font1.Dispose();

But as pointed out by Casey, it actually ensures the object is disposed of, even if an exception is thrown inside the block i.e.

var font1 = new Font("Arial", 10.0f);
try
{
    byte charset = font1.GdiCharSet;
}
finally
{
    if (font1 != null)
    {
        font1.Dispose();
    }
}

Answered By – Johnathan Barclay

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.