Reputation: 477
I've got a base class and three subtypes that derive from that class (see example below).
public abstract class Vehicle
{
string name;
string color;
}
public class Car : Vehicle
{
int nrofwheels;
}
public class Train : Vehicle
{
int nrofrailcars;
}
To make one of my method as generic as possible, I'd like to pass the base type as parameter and then detect hat subtype it is inside my method like this:
public static void main(string[] args)
{
public Car c = new Car();
public Train t = new Train();
public CheckType(Vehicle v)
{
if(v.GetType()==typeof(Car)) Console.Write(v.nrofwheels);
else Console.Write(v.nrofrailcars);
}
}
This doesn't seem to work, why and what else can I try?
[edit] I know that the class examples aren't complete, but I'd figured that its not necessary for this purpose.
Upvotes: 0
Views: 166
Reputation: 156958
You can use as
. You forgot to cast the object to make the properties accessible:
public CheckType(Vehicle v)
{
Train t = v as Train;
if (t != null)
Console.Write(t.nrofrailcars);
else
{
Car c = v as Car;
if (c != null)
Console.Write(c.nrofwheels);
}
}
Upvotes: 0
Reputation: 20693
You should refactor that class and move CheckType to Vehicle class and override it in descendant classes. And CheckType name is not the best one, it makes no sense since that method returns number of wheels / rails.
Something like this:
public abstract class Vehicle
{
string name;
string color;
public abstract int CheckType();
}
public class Car : Vehicle
{
int nrofwheels;
public override int CheckType()
{
return this.nrofwheels;
}
}
public class Train : Vehicle
{
int nrofrailcars;
public override int CheckType()
{
return this.nrofrailcars;
}
}
Upvotes: 7