Runtime Type Identification in C#

By Mahak Gupta Blogs | C# Language Sep 02, 2012
In this blog I am going to explain how to create runtime type identification in C#.
Download Files: RTID.rar

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");

              }

       }

}

COMMENT USING

PREMIUM SPONSORS

Hire Mobile & Web Developer on demand. 100% satisfaction. Try for 1 week or Money Back. Local and remote developers available all over USA.

Latest Blogs