Tuesday, April 27, 2010

using statement in C#

This is a nice little statement which reduces our coding and minimises prone to errors.
There are many situations we have to Dispose the object we created. Example

string connString = "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=MyDB;";

SqlConnection myConnect = new SqlConnection(connString);
SqlCommand cmd = myConnect.CreateCommand();
cmd.CommandText = "SELECT * FROM MyTable";

myConnect.Open();

SqlDataReader dr = cmd.ExecuteReader();

while (dr.Read())
{
Console.WriteLine("{0}\t{1}", dr.GetString(0), dr.GetString(1));
}

dr.Dispose();
myConnect.Close();
myConnect.Dispose();

Here on above example I just try to connect to a database and take out all records from MyTable.


I have created a SqlConnection object named myConnect  and a SqlDataReader object named dr, at the very bottom of the code snippet I have disposed those two objects using Dispose() method.


What will happen if I forget to dispose these objects? memory issues, using statement is a remedy for this and its makes code more readable, robust and clean. I will recode the above code snippet with using “using ” statement.

using (SqlConnection myConnect = new SqlConnection(connString))
{
SqlCommand cmd = myConnect.CreateCommand();
cmd.CommandText = "SELECT * FROM MyTable";

myConnect.Open();

using (SqlDataReader dr = cmd.ExecuteReader())
{

while (dr.Read())
{
Console.WriteLine("{0}\t{1}", dr.GetString(0), dr.GetString(1));
}
}
}

Don’t you feel more comfortable with using statement? Let me just go bit deep on using statement, how does this work? Actually when an using statement compiled, the CLR converts it to a try and Finally block. It does three things, get the resources (SqlConnection ), encloses in a try block and disposes in the Finally block. Hope you enjoyed …………….

2 comments:

Avantha Siriwardana said...

yes this is easy rather using that long way path. :)

d said...

i like this

www.richonet.com
www.bwtrp.com
www.oracledba.in

My Achievements

Member of

Blog Archive

Followers