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.

Advertisements

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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

iReadable { }

.NET Tips & Tricks

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: