Home › Dynamics 365 Customer Engagement (CRM) › C# – TypeOf, GetType, Is
Dynamics 365 Customer Engagement (CRM) · Sep 7, 2016 · 2 MIN READ

C# – TypeOf, GetType, Is

In C#, there are different ways to detemine the type of an object or type itself. These include typeof, GetType and Is.

We would use typeof if we are trying to determine the type of a class, interface, array, enum etc. Typeof does not accept variables as a parameter. This is specified at compile time.

If we are trying to determine the type of a variable, we would use GetType. This is used at runtime.

We can also use is to determine if an object is a type.

Consider the examples below. We have 2 variables, Vehicle v and Car c. We can check the types:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Carl.TypeOf
{
    class Program
    {
        class Vehicle { }
        class Car : Vehicle { }

        static void Main(string[] args)
        {
            Vehicle v = new Vehicle();
            Car c = new Car();

            Console.WriteLine("TypeOf: {0}", typeof(Vehicle));
            Console.WriteLine("TypeOf: {0}", typeof(Car));

            Console.WriteLine("GetType: {0}", v.GetType());
            Console.WriteLine("GetType: {0}", c.GetType());

            if (v is Vehicle)
                Console.WriteLine("v is Vehicle");

            if (c is Car)
                Console.WriteLine("c is Car");

            if (v is Car)
                Console.WriteLine("v is Car");

            if (c is Vehicle)
                Console.WriteLine("c is Vehicle");

            Console.ReadLine();
        }
    }
}

Running this produces:

Notice that v is not type Car, but c is type Vehicle. This is due to the inheritance of the classes in this example.

 

Carl de Souza
Keep learning. Keep building.

Explore AI, agents & Microsoft technology.

I share practical ideas, tutorials, and videos about AI, AI agents, Microsoft technologies, and the Power Platform.

Subscribe on YouTube →
Carl de Souza Enterprise Architect at Microsoft · AI Technology Expert

Leave a Reply

Your email address will not be published. Required fields are marked *

Carl de Souza
KEEP LEARNING. KEEP BUILDING.

Explore AI, agents & Microsoft technology.

I share practical ideas, tutorials, and videos about AI, AI agents, Microsoft technologies, and the Power Platform.