I would like to make a a List
in which I can put multiple different structs. The problem is that I can't give the List
the template argument, as the struct have no common denominator (and inheritance of structs isn't possible). I mean something of the following:
struct Apple
{
float roundness;
float appleness;
}
struct Orange
{
float orangeness;
bool isActuallyAMandarin;
}
List<???> fruitBasket;
void Main(string [] args)
{
fruitBasket = new List<???>();
fruitBasket.Add( new Apple());
fruitBasket.Add( new Orange());
}
Leaving out the List's template argument gives, for obvious reasons, the error:
Using the generic type 'System.Collections.Generic.List<T>' requires 1 type arguments
Is there a way of doing this? Perhaps with a List
or perhaps with an array or different collection class that doesn't require the type argument?
Edit: This question is specifically about structs, not about classes. I am fully aware of the fact this could be solved with classes and inheritance, but I am simply not at the liberty to use classes instead (3rd party library issues...).
There's one class that's base for each structure: it's Object
, so you can put it
List<Object> fruitBasket;
but it means boxing each structure in the list. Yet another possibility is
List<ValueType> fruitBasket;
you can make use of interfaces here!
public interface IFruit {}
Apple : IFruit {...}
Orange : IFruit {...}
List<IFruit> list = new List<IFruit>();
list.Add(new Apple());
list.Add(new Orange());
Though, it would still cause boxing operation (interface being reference type)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With