How to identify the type of Object or the Class at runtime in C#

Runtime type identification of any object is useful for many reason such as when you need to casting of the objects or when you use the base class, you can get the what type of the object is being referred to by a base class reference. Another is when you need to perform various operation according to type of object.
 
In this article we will learn that how we can determine the identity of the object with the help of typeOf, As and Is operator.
 

Get Information about type of the Class

Consider the following example:

using System;
using System.Reflection;
namespace ConsoleApplication1
{
    class ExampleTypeOf
    {
        //......
    }
    class Program
    {
 
        static void Main(string[] args)
        {
 
            System.Type objType = typeof(ExampleTypeOf);
 
            Console.WriteLine("the full name of the ExampleTypeOf is " + objType.FullName);
            // you can get the more information about the ExampleTypeOf
            if (objType.IsAbstract)
            {
                Console.WriteLine("ExampleTypeOf is abstract class");
            }
            if (objType.IsArray)
            {
                Console.WriteLine("ExampleTypeOf is array");
            }
            if (objType.IsClass)
            {
                Console.WriteLine("ExampleTypeOf is class");
            }
 
            Console.ReadKey();
        }
    }
}

The Output of the above program will shown as :
the full name of the ExampleTypeOf is ConsoleApplication1.ExampleTypeOf
ExampleTypeOf is class
 

Determine type using Is operator

You can determine if an object is of a certain type with the help of is operator, You can use Is operator as :
expression is type
Where expression is an expression of a reference type and type is a type. See the following example:

public class Program
{
    private static void Main(string[] args)
    {
        double objVal = 786.58;
        GetType(objVal);
    }
    private static void GetType(object obj)
    {
        if (obj is int)
        {
            Console.WriteLine("objVal is Int");
            //do action
        }
        if (obj is double)
        {
            Console.WriteLine("objVal is double");
            //do action
        }
        if (obj is float)
        {
            Console.WriteLine("objVal is float");
            //do action
        }
        Console.ReadKey();
    }
}

The Output of the above program will shown as :
objVal is double
 
Note that the is operator only considers reference conversions, boxing conversions, and unboxing conversions. Other conversions, such as user-defined conversions, are not considered by the is operator.

Example