Getting the type of an object in .NET C#
December 24, 2016 2 Comments
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:
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.
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
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