As a directive, when it is used to create an alias for a namespace or to import types defined in other namespaces. See using Directive.
As a statement, when it defines a scope at the end of which an object will be disposed. See using Statement.
Using 'using'
A typical scenario where we could use the using statement is :
Collapse
string connString = "Data Source=localhost;Integrated " +
"Security=SSPI;Initial Catalog=Northwind;";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT ID, Name FROM Customers";
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
Console.WriteLine("{0}\t{1}", dr.GetString(0), dr.GetString(1));
}
}
Note
The using statement is only useful for objects with a lifetime that does not extend beyond the method in which the objects are constructed. Remember that the objects you instantiate must implement the System.IDisposable interface.
There is no equivalent for the using statement in vb.net. You have to use the try finally block.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment