Home > DeveloperSection > Forums > The "using" Keyword in C#
Pravesh Singh
Pravesh Singh

Total Post:101

Points:709
Posted on    November-17-2012 7:03 AM

 C# C# 
Ratings:


 2 Reply(s)
 1935  View(s)
Rate this:
Hi Guys 

Please tell me the "using" Keyword in C#

thanks



AVADHESH PATEL

Total Post:604

Points:4228
Posted on    November-19-2012 12:43 AM

hi Pravesh

The reason for the "using" statement is to ensure that the object is always disposed correctly, and it doesn't require explicit code to ensure that this happens.
{ // 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();
    }
}

We can write above code like this

using (MyResource myRes = new MyResource())
{
    myRes.DoSomething();
}

Shankar M

Total Post:25

Points:175
Posted on    February-09-2013 4:25 AM

The Using Keyword takes care of freeing the resources automatically associated with the block.

Don't want to miss updates? Please click the below button!

Follow MindStick