Several Uses of using Instruction in C

  • 2021-08-21 21:09:51
  • OfStack

Usage of using instruction in C #

1. using directive

using + Namespace name, so that you can use the type in the command space directly in the program without specifying the detailed namespace of the type. Similar to import of Java, this function is also the most commonly used, and almost every cs program will use it.

For example:


using System; 
using System.Data; 

2. using alias

using + Alias = a concrete type that includes detailed namespace information.

The advantage of this approach is when the same cs refers to two different namespaces, but both namespaces contain a type with the same name. When this type is needed, it is necessary to use detailed namespaces to distinguish these types with the same name everywhere. The method of using alias will be more concise, and it is ok to make alias declaration for which class.

Note: It is not that two names are duplicate. If one of them is aliased, the other one does not need to be aliased. If both are used, both need to use using to define aliases.

For example:


using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using aClass = ConsoleApplication1.MyClass; 
using bClass = ConsoleApplication2.MyClass; 
namespace ConsoleApplication1 
{ 
public 
class MyClass 
{ 
public 
override 
string ToString() 
{ 
return "You are in ConsoleApplication1.MyClass"; 
} 
} 
class TestUsing 
{ 
} 
} 
namespace ConsoleApplication2 
{ 
class MyClass 
{ 
public 
override 
string ToString() 
{ 
return "You are in ConsoleApplication2.MyClass"; 
} 
} 
} 
namespace TestUsing 
{ 
using ConsoleApplication1; 
using ConsoleApplication2; 
class ClassTestUsing 
{ 
static 
void Main() 
{ 
aClass my1 = new aClass(); 
Console.WriteLine(my1); 
bClass my2 = new bClass(); 
Console.WriteLine(my2); 
Console.WriteLine("ress any key"); 
Console.Read(); 
} 
} 
} 

3. using statement, which defines a scope and processes objects at the end of the scope

Scenario:

When you use an instance of a class in a code snippet, you want to automatically call the Dispose of that class instance whenever you leave the code snippet for whatever reason.

To do this, it is possible to catch exceptions with try... catch, but it is also convenient to use using.


public 
static DataTable GetTable(string sql, int executeTimeOut, string connStringName) 
{ 
DataTable dtRet = new DataTable(); 
using (SqlConnection sc = new SqlConnection(connStringName)) 
{ 
using (SqlDataAdapter sqa = new SqlDataAdapter(sql, sc)) 
{ 
sqa.SelectCommand.CommandTimeout = executeTimeOut; 
sqa.Fill(dtRet); 
return dtRet; 
} 
} 
} 

I hope that through the introduction of this article, it can bring you help.


Related articles: