Runtime Type Identification in C#

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:

RuntimeTypeIdentification.png

After that, we create a main class TryIs:

class TryIs

{

    public static void main()

    {

        first f = new first();

        second s = new second();

        third t = new third();

        if (s is first)

        {

            Console.WriteLine("It is in the first class");

        }

        if (t is second)

        {

            Console.WriteLine("It is in the second class");

        }

        if (t is first)

        {

            Console.WriteLine("It 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

Ex:

 

using System;

class first

{

}

class second : first

{

}

 

class mainclass

{

    public static void main()

       {

              first f=new first();

              second s=new second();

              s=f as s;

              if(s==null)

              {

                     Console.WriteLine("type casting is not allowed");

             

              }

              else

              {of the

                     Console.WriteLine("type casting is allowed");

              }

       }

}

Ebook Download
View all
Learn
View all