Explain the importance of Using keyword and Using Statement in C#

 Posted by Rajnilari2015 on 8/16/2016 | Category: C# Interview questions | Views: 302 | Points: 40
Answer:

In C# parlance, Using can be use in two ways

a) As a directive where it's behavior will be as inclusion of a namespace. e.g.

using System; //import namespace

using System.IO;
using Item = System.Collections.Generic; //creating alias for namespace
namespace UsingNamespaceDemo
{
public class TestUsingClass
{
//observe Item.List where Item is an alias of System.Collections.Generic namespace
var intItemList = new Item.List<int>(){1,2,3,4,5};
foreach(var item in intItemList) Console.WriteLine(item);
}
}


b)As a statement that can only be used with types that implement IDisposable interface.
e.g.
string connString = "Data Source=abc;Integrated Security=SSPI;Initial Catalog=db;";

using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM tblTest";
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
Console.WriteLine("{0}", dr.GetString(0));
}
}

It can also be consider as a syntactic sugar(short hand version) for try/finally block e.g.
using (SqlConnection conn = new SqlConnection(connString))

{
//do something
}
is same as

SqlConnection conn = new SqlConnection(connString);

try
{
//do something
}
finally
{
if(conn != null)
{
conn.Dispose();
}
}


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response