The "using" Keyword in C#

Total Post:101

Points:709
C# 
C#
 2654  View(s)
Ratings:
Rate this:
Hi Guys 

Please tell me the "using" Keyword in C#

thanks
  1. Post:604

    Points:4228
    Re: The "using" Keyword in C#

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

      Modified On Mar-29-2018 06:24:01 AM
  1. Post:25

    Points:175
    Re: The "using" Keyword in C#

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

Answer