Getting the type of an object in .NET C#

You’ll probably know that every object in C# ultimately derives from the Object base class. The Object class has a GetType() method which returns the Type of an object.

Say you have the following class hierarchy:

public class Vehicle

public class Car : Vehicle

public class Truck : Vehicle

Then declare the following instances all as Vehicle objects:

Vehicle vehicle = new Vehicle();
Vehicle car = new Car();
Vehicle truck = new Truck();

Let’s output the type names of these objects:

Examining type of derived objects

So ‘car’ and ‘truck’ are not of type Vehicle. An object can only have a single type even if it can be cast to a base type, i.e. a base class or an interface. You can still easily get to the Type from which a given object is derived:

Type truckBase = truckType.BaseType;
Console.WriteLine("Truck base: {0}", truckBase.Name);

…which of course returns ‘Vehicle’.

View all posts on Reflection here.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

2 Responses to Getting the type of an object in .NET C#

  1. ramessesx says:

    Hi Andras -> Thank you for yet another well explained post, I’ve learned a lot from you this year and hope this continues next year, happy holidays, my best to you and your family, take care

    • Andras Nemes says:

      Hello Pharaoh Ramesses, thanks for your kind words. It’s flattering that even ancient rulers are getting useful information from this blog :-). Merry Christmas and all the best to you as well! Andras

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: