1. concept description
Is the operator used in C # To determine type compatibility. Check whether an object is compatible with other specified types. If an object is of a certain type or its parent type, true is returned, otherwise, false is returned.
Is rules are as follows:
Check the compatibility of object types and return results, true or false;
No exception is thrown;
If the object is null, the return value is always false.
Example
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 following code.
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.
As is the operator used in C # for determining type compatibility and type conversion. It also performs type judgment and type conversion. It can simplify the Code while improving the performance.
The as rules are as follows:
Check the compatibility of object types and perform forced conversion. Return results. If not, return null;
No exception is thrown;
If the result is null, The NullReferenceException is thrown when the type conversion is forced.
Employee e = o as Employee;
If (e! = Null)
{
// Use e in the if statement
}
This as operation only performs one type check, which improves the performance. If the types are the same, a non-null reference is returned. Otherwise, an empty reference is returned.