SoFunction
Updated on 2025-03-07

c# type conversion

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

However, if an object is converted to its own derived type, an error will be reported during runtime:
object o = new object();
Emplee e = (Emplee)o;

So CLR is type safe.

The usage of the operator of is as in c#
In C# language, another way to perform type conversion is to use the is as operator.
is: Check whether the object is compatible with the specified object and returns the bool type.
example:

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


is general usage:
if(o is Emplee)
{
Emplee e = (Emplee)o;
}
as: The purpose is to simplify the code writing of is and improve performance. Usage:
Emplee e = o as Emplee;
if(e != null)
{ }
In this code, the CLR verifies whether o is compatible with the Emplee type. If compatible, it will be converted to the Emplee type, and if incompatible, it will be returned to null.