C# – TypeOf, GetType, Is

Leave a comment

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.

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube

 

Leave a Reply

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