c type conversion

  • 2020-05-07 20:18:59
  • OfStack

CLR allows an object to be converted to its actual type, or its base type.
In C#, you can implicitly convert an object to its base type, and converting an object to a derived type requires the conversion to be shown. Ex. :
object o = new Emplee();
Emplee e = (Emplee)o;

However, if an object is converted to its own derived type, it will run the error:
object o = new object();
Emplee e = (Emplee)o;

So CLR is type safe.

The use of the operator is as in c#
Another way to cast in c# is to use the is as operator.
is: checks whether the object is compatible with the specified object, returns the bool type.
Ex. :

object o = new object();
bool b1 = (o is object);//true
bool b2 = (o is Emplee);//false


is1-like usage:
if(o is Emplee)
{
Emplee e = (Emplee)o;
}
as: the purpose is to simplify the coding of is while improving the performance. Usage:
Emplee e = o as Emplee;
if(e != null)
{ }
In this code, CLR verifies that o is compatible with Emplee type; if it is, it goes to Emplee type; if not, it returns null.

Related articles: