What is the best way to solve this?
A static member is one for all subclasses and i want a different static member for subclasses but with the same name so I can use vehicle.canDo; this should give me different arrays depending what class the vechicle instance really is.
I can just remove the static from canDo array but all instances of the same subclass should always have the same values in the canDo array so there is no need to have canDo array in every instances, this will be big waste of memory because i will have too many instances of this class.
class Vehicle {
public static List<string> canDo;
static Vehicle() {
canDo = new List<string>();
canDo.Add("go");
}
}
class Plane : Vehicle {
static Plane() {
canDo.Add("fly");
}
}
class Ship : Vehicle {
static Ship() {
canDo.Add("sail");
}
}
class Main {
static void Main(string[] args) {
Vehicle plane = new Plane();
Vehicle ship = new Ship();
plane.canDo; // Contains (go, fly and sail) i want only (go and fly)
ship.canDo; // Contains (go, fly and sail) i want only (go and sail)
}
}
You need an instance of the
canDolist per type. So either you can pass in the collection via the constructor or you can have a static on the subtype level.Edit (to elaborate):
Since your sub class instance all have the same ‘abilities’ and you don’t want to populate a list for each you would need a shared list. You are using inheritance where you probably want composition:
I wouldn’t go with a
List<string>either but rather encapsulate it in a class that makes business sense (although I understand that this is only an example). To populate thecanDolist you could go with a factory or a factory method on a subtype.There are just so many ways to do this you will need to find something that’s comfortable.
Although I did present a static as an alternative (since you were asking about it) I definitely would not use a static for this myself.