Runtime Type Identification in C#
Here we discuss about a feature of C# called RTID (Runtime Type Identification).
With the help of this, we can identify a type of an object during the execution
of the program. And we can easily get that the casting is possible or not.
There are three keywords, which supports
Runtime Type Identification: is, as and type of.
Now we will be discussing about this:Using is: The syntax of the is keyword is :
expr is Type
Here expr is the expression, which type is tested against the Type.
For ex: In this example we create three
classes (first, second, third), here second and third derived from the first
class, in this program we will check that the following classes will be derived
from the first class:
After that, we create a main class TryIs:
first f =
second s =
third t =
if (s is first)
is in the first class");
if (t is second)
is in the second class");
if (t is first)
is in first class");
In the class first we create the object of the class and then we
check the type Identification.
The Output Will be:
It is in the first class
Using as: The syntax of the as keyword is :
expr as Type
class second : first
casting is not allowed");
casting is allowed");