Getting the type of an object in .NET C#
September 26, 2014 1 Comment
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,
maybe you should point out the static and dynamic type of an object?
The dynamic type is Car or Truck. But the static type is indeed Vehicle.