Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have a List of different structs?

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...).

like image 987
Yellow Avatar asked Sep 18 '25 21:09

Yellow


2 Answers

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;
like image 70
Dmitry Bychenko Avatar answered Sep 21 '25 11:09

Dmitry Bychenko


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)

like image 45
Manish Basantani Avatar answered Sep 21 '25 12:09

Manish Basantani