CLR allows an object to be forcibly converted to its original type or any base type. C # explicitly convert an object to any of its derived types, because such a transformation may fail at runtime. BelowCodeDemonstrate how to convert to base type and derived type:
UsingSystem;
Internal Class Employee
{
//...
}
Public Sealed Class Program
{
Public Static VoidMain ()
{
// No transformation is required, because new returns an employee object, and the object is the base type of the employee.
ObjectO =New Employee();
// Transformation is required because the employee is derived from the object
EmployeeE = (Employee) O;
}
}
Convert using is and:
The is operator checks whether an object is compatible with the specified type and returns a Boolean value, as shown below:
ObjectO =New Employee();
Boolean b1 = (O is Object ); // B1 is true
BooleanB2 = (oIs Employee);// B2 is false
If the object reference is null, the is Operator always returns false. The is operator is usually used as follows:
If (O is employee )
{
EmployeeE = (Employee) O;
//... Use E
}
In this Code, the CLR checks the object type twice. The is operator first checks whether o is compatible with the employee type. If yes, when the if statement content is transformed, CLR checks whether o references an employee again, which has a certain impact on the row performance, because CLR must first determine the actual type of the object referenced by variable O. Then, CLR must traverse the inheritance hierarchy and use each base type to check the specified type of employee. In this regard, C # provides the as operator, which not only simplifies writing, but also improves performance.
EmployeeE = oAs Employee;
If(E! =Null)
{
//... Use E
}
In the preceding code, CLR first checks whether o is compatible with the employee type. If yes, as returns a non-null reference to the same object. If not, null is returned, the Code CLR only verifies the object type once, greatly improving the performance.