There are two operators "is" and "as" to judge and convert types. The specific differences and usage are as follows:
Is in the judgment of the type. Returns true and false. If an object is of a certain type or its parent type, true is returned; otherwise, false is returned. In addition, the is operator will never throw an exception. The Code is as follows:
System. Boolean b1 = (o is System. Object); // b1 is true
System. boolean b2 = (o is Employee); // b2 is false if the object reference is null, the is Operator always returns false because no object can check its type, just like the code below
If (o is Employee ){
Employee e = (Employee) o;
// Use e in the if statement
} In the code above, clr checks the object type twice: The is operation first checks whether the object referenced by o is compatible with the employee type. If it is compatible, the clr in the if statement checks whether o is referenced by an Employee when executing the conversion. This programming paradigm is very common. c # provides a new type check and conversion method. That is, the as operator can improve the performance while simplifying the code. The Code is as follows:
Employee e = o as Employee;
If (e! = Null)
{
// Use e in the if statement
} This as operation improves the performance even if it is equivalent to the above Code and performs only one type check at the same time. If the types are the same, a non-null reference is returned. Otherwise, an empty reference is returned.