.Net Articles

the "Using" statement in C#

1. using + namespace:

So you can use the type under the namespace directly, without type in the full namespace name. similar with Jave's Import.
Example: using System.Data;

2. using + Alias Name = full type name.

when to use: You can use this when you using 2 different namespaces in 1 cs file. but these 2 different namespaces contains a type with same name.
example:
using aClass = NameSpace1.MyClass;
using bClass = NameSpace2.MyClass;

3. using statement, to auto dispose the object.

You create an instance in a using statement to ensure that Dispose is called on the object when the using statement is exited. A using statement can be exited either when the end of the using statement is reached or if, for example, an exception is thrown and control leaves the statement block before the end of the statement.

The object you instantiate must implement the System.IDisposable interface. 

example:
using (Class1 cls1 = new Class1(), cls2 = new Class1())
{
// the code using cls1, cls2


} // call the Dispose on cls1 and cls2 

this is very useful, when you want to close database connection or transaction.

alternatively you can use try .. catch, but use "using" is so simple and clear.

2/5/2008 3:51:23 AM Published by FengLiN Category C Sharp(C#) Comments 0 Views (921)
Name

Web site

Are you human? Enter the verify code below.

Comment