Deep understanding of type conversion in.NET

  • 2020-05-19 04:40:01
  • OfStack

One of the most important features of CLR is type safety. CLR always knows the type of an object at run time. We can also get the exact type of the object by calling the GetType() method. Since this method is a non-virtual method, it is not possible to manipulate a type of information with it. (Microsoft.NET framework programming < revision > p117)

We define the following classes:


 public class Employee   
  {
     string name= string.Empty;
     float age = -1;
     public override string ToString()
     {
         return "name = "+name +" and age = "+age;
     }
 }
 

Through the following code:

 Employee e = new Employee();
 object oe = e as object;
 if(oe == null)
 {
     Console.WriteLine("oe is null");
 }
 Console.WriteLine("oe's type is : {0}",oe.GetType());
 

From the above, it should be clear that "CLR always knows the type of an object at run time." .
The as operator provides a compatibility check for the left instance to the right type, and returns a reference to that object if the left instance can be converted to the right type, otherwise returns null. In addition to the as operator, the is operator is also provided in C#, which also provides a compatibility check between the instance on the left and the type on the right, except that when the result is compatible, it returns true, otherwise it returns false, so it needs an additional display operation to complete the conversion. So the as operator is relatively efficient. In addition, neither operator throws an exception while running. However, the as operator requires the determination of whether the transformed object is an null reference to prevent null reference operations in the event of unsuccessful conversion.

Because the as operator returns null when the validation result is incompatible, the as operator cannot verify the instance against the value type, otherwise the compilation will fail. Because the value type cannot be assigned to null(? Except).


Related articles: