Let's say I have a base class named BaseClass:
public BaseClase{
public bool isCool;
}
Now let's say I have two classes that inherit from BaseClass
public Class1: BaseClass{
public bool isGreen;
}
public Class2: BaseClass{
public bool isPurple;
}
Now let's say I want to create a list that contains instances of both Class1 and Class2 by creating a List;
var genericList = new List<BaseClass>();
Next, let's add an instance of Class1 and Class2 to genericList.
genericList.Add(new Class1());
genericList.Add(new Class2());
Now, here is what I have a question about. If I want to access Class1.IsGreen or Class2.IsPurple, I have to cast each item in genericList as Class1 or Class2.
foreach(var item in genericList){
if(item is Class1){
var temp = (Class1) item;
temp.IsGreen = true;
}
if(item is Class2){
var temp = (Class2) item;
item.IsPurple = true;
}
}
Is this just the way you're supposed to do things? It seems very clunky to me, and the complexity of the code I'm writing that uses this type of code structure is getting out of hand. I'm new to inheritance, and want to learn if this is just the way you're supposed to do things, or if there are better alternatives out there.