There are mainly the following ways to use keywords in C#.
1. Introduce namespace
For example: using System, it is used in almost every class.
2. Alias the introduced namespace
using + alias = specific type including detailed namespace information
using aClass = ; using bClass = ;<br>
Advantages: When the same cs refers to two different namespaces, but both namespaces include a type with the same name. When this type is needed, each place needs to use a detailed namespace method to distinguish these types of the same name. The method of using alias will be more concise. Just declare the alias for which class you use. Note: It does not mean that two names are repeated. If one is given an alias, the other one does not need to use an alias. If both are to be used, both need to use using to define alias.
3. Automatically release the created object
effect:
1. Automatically release unmanaged resources to avoid cache and memory overflow, allowing programmers to specify when objects that use resources should release resources.
2. Simplify try catch to automatically release the newly created object within this definition domain to simplify the code;
Essence: During the program compilation stage, the compiler will automatically generate the using statement into a try-finally statement, and call the object's Dispose method in the finally block to clean up the resources. Therefore, the using statement is equivalent to a try-finally statement.
Font f2 = new Font("Arial", 10, ); try { } finally { if (f2 != null) ((IDisposable)f2).Dispose(); }
Notes:
1. The objects used in brackets must implement the IDisposable interface. This interface provides a Dispose method, which releases the resource of this object. It is prohibited to use using statements for types that do not support the IDisposable interface, otherwise a compilation error will occur.
using (MemoryStream ms = new MemoryStream()) { (ms, ); returnImageData = (); (); }
Statements are suitable for cleaning a single unmanaged resource, while cleaning up multiple unmanaged objects is best done in try-finnaly, because nested using statements may have hidden bugs. When an exception is raised by an inner using block, the object resources of the outer using block will not be released.
Statements support initializing multiple variables, provided that the types of these variables must be the same, for example:
using(Pen p1 = new Pen(), p2 = new Pen()) { }
4. When initializing variables of different types, they can be declared as IDisposable.
using (IDisposable font = new Font("Verdana", 12), pen = new Pen()) { float size = (font as Font).Size; Brush brush = (pen as Pen).Brush; }
Life is like a journey, I am also a pedestrian
This is the article about how to use using in C#. For more related content on using using in C#, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!