Analysis of the use of is and as keywords in type conversion, analysis of
Is checks whether the object is compatible with the specified type and returns a Boolean value of true or false. It is worth noting that when using is for type conversion, an exception will never be thrown. For example:
Object o = new Object ();
Boolean a = (o is object); // returns a = true
Boolean B = (o is Employee) // return B = false
If the object is null, the returned result is false because no object of its type can be checked and null is not an object.
Common usage of the is OPERATOR:
If (o is Employee ){
Employee e = (Employee) o; // type conversion
}
In the above Code, the o object is checked for two types. The is operator first checks whether o is compatible with the Employee type. if yes, during internal conversion of the if statement, CLR (when the common language is running) checks again whether o references an Employee. CLR type checks enhance security, but undoubtedly cause some performance loss,
Therefore, C # provides the AS operator to simplify the code writing and improve performance.
Employee e = o as Employee;
If (e! = Null ){
// Use e
}
In this Code, CLR checks whether o is compatible with the Employee type. If yes, as returns a non-null reference to the same object. If it is not compatible with the Employee type, as returns null, so that CLR only verifies the object type once, which is much faster than is.
The as operator works in the same way as forced type conversion, but it never throws an exception. If the object cannot be converted, null is returned, therefore, before using the as conversion type, you must determine whether the object is null. Otherwise, an exception occurs, such:
Object o = new Object ();
Employee e = o as Employee; // type conversion failed here, e = null; no exception is thrown
E. Tostring (); // use e to throw NullReferenceException