Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Test if a class in an instance of a super class instead of a subclass

Tags:

c#

inheritance

I have a class, which has a bunch of subclasses that inherit from it. How can I test to see whether an object is an instance of that super class, and not of any of the derived classes?

Example:

I have a Vehicle class, and it has several classes that inherit from it, like Car, Motorcycle, Bicycle, Truck, etc.

Assuming this, how do I test to see if a Vehicle object is really of the class Vehicle, and not Car or Bicycle? (Since a Car and a Bicycle are in this case an instance of the Vehicle class, too.)

like image 865
Lars Avatar asked Apr 07 '11 19:04

Lars


1 Answers

if (theObject.GetType() == typeof(Vehicle))
{
   // it's really a Vehicle instance
}
like image 98
Fredrik Mörk Avatar answered Sep 29 '22 10:09

Fredrik Mörk