Create Objects by using C# using Statement

In general we create the object for any class by using ClassName objectName=  new ClassName(). If we create the object like this, we have to dispose the object manually by calling Dispose() method. If we create the object by using C# using statement, Dispose() method automatically will get called.

Open Microsoft Visual Studio2015 => Create Console Application and name it as CSharpUsing. Add code to Main() method as shown below.

using System.Data.SqlClient;

namespace CSharpUsing

{

    class Program

    {

        static void Main(string[] args)

        {

            SqlConnection sqlCon = new SqlConnection("Data Source=(local);Initial Catalog=Northwind;Integrated Security=true;");

        }

    }

} 

To dispose the object, we have to call Dispose method like sqlCon.Dispose();. Let’s observe MSIL(Microsoft Intermediate Language) code without calling Dispose() method. Build the project, open Visual Studio command prompt and enter ildasm command, it opens ILDASM window as shown below.

Open CSharpUsing.exe by going File => Open CSharpUsing.exe it displays window IL code. Double click on CSharpUsing => double click on Main() method, it opens IL code for our C# code as shown below.

Here we do not have any Dispose() method called. Now let’s change our C# code to create an object by using C# using the statement as shown below.

using System.Data.SqlClient; 

namespace CSharpUsing

{

    class Program

    {

        static void Main(string[] args)

        {

            using (SqlConnection sqlCon = new SqlConnection("Data Source=(local);Initial Catalog=Northwind;Integrated Security=true;"))

            { 

            }          

        }

    }

} 

Check MSIL code for Main() method, it displays as shown below.

As indicated above, try & finally, statement got created and Dispose() method getting called in a finally statement. That means if we create the object through using statement, the object automatically get disposes after usage. The important thing to remember, we can create an object through C# using statements for only classes which implement the IDisposable interface.