Hello, I have a bit of a data storage problem. I have a system that needs to be able to store a lot of data of different types in the same Dictionary<>. The classes are mostly same, except for one or two details. Hence it doesn’t make sense to have as hundred copies of them.
For simplicity, and to reuse code, what I would like to do is either:
- Create a List or Dictionary that can store several different inherited classes at once.
- Create a class that has ‘slots’ that can contain generic data, which I establish when the class is built.
To clarify: I will always know what type of class I’m retrieving before I retrieve it because of a ‘type’ variable. This is as much me trying to learn about generic types as it is me being trying to be efficient and not keep repeating the same things.
Can anyone help?
This sounds suspiciously like you should be looking into the Strategy Pattern. But regardless of that, is there a reason you can’t just use interfaces? Or good old covariance/contravariance?
A quick and dirty method to implement the strategy pattern would be to just create an interface or abstract base class that each of them derives from. Then at runtime you can just pop them into a list or dictionary. If there really is unique data/functionality per sub-class then when you go through the collection you can just cast to the appropriate type and go from there.
I don’t think it needs to be as complex as a Strategy Pattern. I’ve used interfaces a little, but not sure. What would be the official non-hacky way to do this do you think?
Ah! Thank you! That turned out to be what I’m after.
Yes it looks like I can do this. This is working, thank you.
List<BaseClass> list = new List<BaseClass>();
list.Add(new DerivedClass());
foreach (var item in list)
{
if (item is DerivedClass derived)
{
derived.DerivedMethod();
}
}