Techbubbles

Using keyword in C#

Introduction

Using keyword in C# can be used as directive and as well as statement.

When you use using as Directive you will get the following advantages

  • You can use the types in a namespace by declaring with using keyword.

        example: using Systetm.Web;

 

  • You can define a alias for the nested namespaces

       example: using alias = CompanyName.ProjectName;

When you use using as Statement it defines the scope and allows the programmer to release the resources used by the object in the defined scope.

The object mentioned in the using statement must implement IDisposable interface. A using statement is can be exited when the end of the using statement is reached.

example :

Font font2 = new Font("Arial", 10.0f);
using (font2)
{
    // use font2
}
Multiple objects can be used in with a using statement, but they must
be declared inside the using statement.

example:

using (ResourceType r1 = e1, r2 = e2, …, rN = eN) statement

it is equivalent to the following code

using (ResourceType r1 = e1)

   using (ResourceType r2 = e2)

      …

         using (ResourceType rN = eN)

            statement

Related Posts:

%d bloggers like this: