Thursday, 21 July 2011

Use of using keyword in C# (.Net)

here are three use of using keywords

1. using directive to use to import namespace in C# class
2. Create a using directive to use the types in a namespace withough having to specify that actual namespace (i.e. using directive creates an alias).
3. To automatically close and dispose any object references implementing the IDisposable interface


A using directive does not give you access to any of the various namespaces that might be nested in the namespace that you specified.

A user defined namespace is referring to any namespace you have created in your code.

Example For 2nd Point:

// using keyword
using System;
using CSF = SomeMain.Resource.ForCSharp; // alias

namespace SomeMain.Resource
{
public class MyClass
{
public static void Something()
{
//empty
}
}

namespace ForCSharp
{
public class MyNestedClass
{
public static void MyMessage()
{
System.Console.WriteLine("CSharpFriends!");
}

}

}

}
public class TestUsing
{
public static void Main()
{
CSF.MyNestedClass.MyMessage();

// pauses output window
Console.ReadLine();
}

}


Example 3rd Point:

using (SqlConnection cn = new SqlConnection(connectionString))
{
// do something
}

is the same as:

SqlConnection cn = new SqlConnection(connectionString)
try
{
// do something...
}
catch
{ }
finally
{
cn.Dispose();
}