Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic collection of generic classes?

I have a class that I fill from the database:

public class Option<T>
{
  public T Value { get; set; }
  public T DefaultValue { get; set; }
  public List<T> AvailableValues { get; set; }
}

I want to have a collection of them:

List<Option<T>> list = new List<Option<T>>();
Option<bool> TestBool = new Option<bool>();
TestBool.Value = true;
TestBool.DefaultValue = false;
list.Add(TestBool);
Option<int> TestInt = new Option<int>();
TestInt.Value = 1;
TestInt.DefaultValue = 0;
list.Add(TestInt);

It doesn't seem to work. Ideas?

like image 600
Adam V Avatar asked Dec 02 '22 06:12

Adam V


1 Answers

I suspect you really want a nongeneric base class - otherwise there's really nothing in common between the different Option<T> closed types.

I understand what you're trying to do, but .NET generics don't allow you to express that relationship. It's like trying to do a map from Type to an instance of that type... it just doesn't fly :(

like image 185
Jon Skeet Avatar answered Dec 04 '22 12:12

Jon Skeet