Using Keyword – Directive & Statement

Using keyword generally comes under the “Namespace Keywords” when we search MSDN on it.

Using keyword used for two main purposes

As a “using” Directive

As a “using” Statement

1) Lets first consider the use of “using” as Directive

– Create an alias for a namespce or to import the namespace

TO import a namespace e.g. using System , using System.Data;

– Create an Alias for Namespaces or Types, generally this concept is used when we are creating the custom namespaces with nested types ,also this concept can be use fot nested classes.

e.g. suppose I have two NameSpaces

namespace Soccer

{

}

namespace Soccer

{

namespace Teams

{

class Player

{

public string PlayerName;

public string PlayerPosition;

}

}

}

namespace Soccer.Management

{

class Coaches

{

public string Name;

public string Experience;

}

}

In this scenario I can use the using keyword with following

Importing namespace.

using Soccer

using Soccer.Teams

Create an Alias.

using SoccerTeams = Soccer.Teams;

we can also access nested namspaces with there classes.

using Coach = Soccer.Management.coaches;

2)As a Using Statement –

This statement is having complete different use than using directive.”Using” statement allows user to specify when to release objects (which are using resources).The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object’s resources.This statement internally calling Dispose() for IDisposable objects like connection,command,so that we dont need to call Dispose() method explicitly.

Lets consider the basic example for Data access in Ado.net –

SqlConnection connection = null;

SqlCommand command = null;

try

{

connection = new SqlConnection(DataAccessBlock.ConnectionString);

command = new SqlCommand(“select * from pubs”, connection);

connection.Open();

command.ExecuteNonQuery();

}

finally

{

command.Dispose();

connection.Dispose();

}

As Command and connection objects are IDisposable objects we need to Dispose them manually to free memory.So when are using “Using” then we dont need to write dispose() statements.

using (SqlConnection connection = new SqlConnection(connectionString))

{

using (SqlCommand command = new SqlCommand(“select * from pubs”, connection))

{

connection.Open();

command .ExecuteNonQuery();

}

}

Note : Object in Using clause must be implementing IDisposable.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s