SoFunction
Updated on 2025-03-07

The use of using and as operators in c# cannot be ignored

Do many people don’t use the using and as operators in C#? They don’t even know?
In fact, these two operators are very useful in small places.

1、using 
According to msdn's explanation

The using statement defines a range, and the object will be processed at the end of this range.
Example:

class TestUsing:IDisposable 
    { 
        public void Dispose()  
        { 
            ("Dispose");  
        } 

        public void Method() 
        { 
            ("Do a method"); 
        } 
    } 
Call this class:


using(TestUsing tu=new TestUsing()) 
            { 
                (); 
            } 
You can see that Do a method and Dispose are output one after another.
Note: Instantiated objects must implement interfaces

2、as 
msdn said this:


The as operator is used to perform conversions between compatible types.
The as  operator is similar to type conversion, the difference is that when the conversion fails, the as  operator will generate empty instead of throwing an exception. Formally, this form of expression:

expression as type 
Equivalent to:

expression is type ? (type)expression : (type)null 
It's just that expression is only calculated once.

Note that the as operator only performs reference conversion and boxing conversion. The as operator cannot perform other conversions, such as user-defined conversions. Such conversions should be performed using a cast expression instead.

 
Example:
object [] arr=new object[2]; 
            arr[0]=123; 
            arr[1]="test"; 
            foreach(object o in arr) 
            { 
                string s=(string)o; 
                (s); 
            } 
Such a code throws an exception when the conversion type fails, and the code is modified to:
object [] arr=new object[2]; 
            arr[0]=123; 
            arr[1]="test"; 
            for(int i=0;i<;i++) 
            { 
                string s=arr[i] as string; 
                if(s!=null)(i+":"+s); 
} You can see that 1:test is output. Although the conversion failed at arr[0], no exception was raised but null was returned.

Note: as must be used with reference types (int equivalent types cannot be used)