Deep understanding of using

Source: Internet
Author: User
Tags finally block
Multiple Using identities
1: Introduce the namespace
2: Create an alias
3: force resource cleanup
(1) Introduce a namespace
Similar to the import commands in Java, using introduces the logical structure of namespaces (called packages in Java). Unlike the # include commands in C, using is used to introduce actual class libraries.
Using introduces a namespace, which is not equal to the Assembly in which the namespace is loaded during compilation by the compiler. The assembly loading is determined by the existence of call operations on the assembly in the program, if no calling operation exists in the Code, the compiler will not load the Assembly where the using namespace is located. Therefore, the introduction of multiple namespaces at the beginning of the source file does not load multiple assemblies and does not cause the "excessive reference" disadvantage.
(2) create an alias
The usage rules for using Using to create aliases are: using MyName = namespace | type. namespace indicates the alias used to create a namespace, and type indicates the alias used to create a namespace.
Create an alias for a namespace
Using mySpace = LyMIT. myCIS. CommonClass;
Create alias for Type
Using MyConsole = System. Console;
MyConsole. WriteLine ("the alias of the applied class. ");
Another important reason for alias creation is that different namespaces introduced in the same cs file contain the same name type. To avoid name conflicts, you can set aliases.
Using to create an alias solves this kind of naming conflict. Of course, you can also distinguish all types by name.
Namespace WindowsApplication1
Using OneClass = ClassLibrary1.Class1;
Using TwoClass = ClassLibrary2.Class1;
Public partial class Form1: Form

Public Form1 ()
InitializeComponent ();
Private void Form1_Click (object sender, EventArgs e)
MessageBox. Show (OneClass. ShowClassInfo );
MessageBox. Show (TwoClass. ShowClassInfo );
(3) Resource cleanup
To understand how to use the using statement to forcibly clean up resources, we should first begin with understanding the Dispose mode. To understand the Dispose mode, we should first understand the. NET garbage collection mechanism. . NET provides the Dispose mode to explicitly release and close objects.
Dispose Mode
The Dispose mode is a Convention provided by. NET to explicitly clean up object resources. It is used to release the unmanaged resources encapsulated by objects in. NET. Because unmanaged resources are not controlled by GC, objects must call their own Dispose () method to release them. This is the so-called Dispose mode. From the conceptual point of view, the Dispose mode is a convention to force resource cleanup. From the implementation point of view, the Dispose mode is to enable an IDisposable interface for a type, this type provides a public Dispose method.

  • The using statement provides a convenient way to forcibly clear object resources, allowing you to specify when to release the object's resource source.
  • All types of unmanaged resources implement the Idisposable interface. If we forget the Dispose () method, the non-memory resources will be released when the Terminator is executed subsequently, in this way, objects are stored in the memory for a long time, and the application cleans up resources slowly.
  • The using statement in C # can be called by the Dispose () method. We can allocate an object in the using statement. The C # compiler will automatically generate a try/finally block for each object.
  • The following code generates the same IL code.

String connStr = string. Empty;
SqlConnection conn = null;
// Using statement example
Using (SqlConnection conn = new SqlConnection (connStr ))
Conn. Open ();
// Try/finally block
Conn = new SqlConnection (connStr );
Conn. Open ();
Conn. Dispose ();
(1) Use the using statement for objects that do not implement the Idisposable () interface.

// The Idisposeable interface is not implemented for the object.
Using (object obj = Factory. CreateResource ())
Console. WriteLine (obj. ToString ());
// Revised version
Object obj = Factory. CreateResource ();
Using (obj as Idsposeable)
Console. WriteLine (obj. ToString ());
If the Idisopose interface is not implemented, the using statement degrades to using (null) in the preceding case. This method is very secure, but does not do anything.
(2) potential resource leakage
SqlConnection conn = new SqlConnection (connStr );
SqlCommand cmd = new SqlCommand (reverse STR, conn );
Using (conn as IDisposeable)
Using (cmd as Idisposeable)
Conn. Open ();
Cmd. ExecuteNonQuery ();
Make sure that all objects implementing the Idisposeable () interface are allocated in the using and Try blocks. Otherwise, memory leakage may occur.
When a method contains multiple objects of resources to be released, you can create multiple using blocks or write a try/finally block by yourself. The two methods are equivalent, the generated IL code is exactly the same.
Some objects implement both Dispose () and Close ().
In addition to releasing resources, Dispose () also notifies the Garbage Collector that the object no longer needs to terminate the operation. Dispose () is implemented through the GC. SuppressFinaize () method. Close () is generally not implemented. Therefore, the object that has called Close () remains in the end queue. Dispose () does not delete the object from the memory, but only releases the object from the unmanaged resources.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.