Introduction:

In this article we will learn what is using statement  in C # or what is the functionality of using statement or how to use using statement in c sharp with example.


Description:

The using statement is used to work with an object in C# that implements the IDisposable interface. The IDisposable interface has one public method called Dispose that is used for dispose of the object. The using statement simplifies the code that you have to write to create and then finally clean up the object. The using statement obtains the resource specified, executes the statements and finally calls the Dispose method of the object to clean up the object. The following An easy example in c# program that demonstrate the using statement very clearly.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
 
namespace Using_Statement
{
    class Method : IDisposable
    {
        public void call()
        {
            Console.WriteLine("Execute call method.");
        }
 
        public void Dispose()
        {
            Console.WriteLine("Dispose the object");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            using (Method c = new Method())
            {
                c.call();
            }           
            Console.ReadLine();
        }
    }
}

 

 

In the above example, the using statement calling the Method class to execute. So, it first executes the call() method and finally executes the Dispose() method to clean up the object.

Output:

How to use using statement in C #

It is generally used in database connectivity through C#. For example the following lines of code using the using statement for database connectivity,

           string  connString = "Data Source=localhost;Integrated " +
            "Security=SSPI;Initial Catalog=Northwind;";
 
            using (SqlConnection conn = new SqlConnection(connString))
            {
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = "SELECT ID, Name FROM Customers";
 
                conn.Open();
 
                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    while (dr.Read())
                        Console.WriteLine("{0}\t{1}", dr.GetString(0), dr.GetString(1));
                }
            }
 

 

I hope this article will helpful to you.

comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

You may also like