views:

173

answers:

4

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?

+10  A: 

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 :(

Jon Skeet
+7  A: 

You have to provide a type instead of your template parameter:

List<Option<T>> list = new List<Option<T>>();

becomes

List<Option<bool>> list = new List<Option<bool>>();

Adding items of type Option<int> to that same list won't work, but that is a separate issue than what I've addressed above.

Jon Seigel
A: 

Firts line you must say wich type T is.

List<Option<bool>> list = new List<Option<bool>>();

And also you can't put that TestInt in this list...

Pedro
A: 

What you're doing only works with heterogeneous lists.

List<T> is an homogeneous list of type T, meaning all elements have to be of type T. Because Option<bool> and Option<int> do not have a common ancestor other than object you can't do that unless you use a List<object> or the old ArrayList, both of which act as heterogeneous lists.

Think of retrieving objects from that list:

list.Add(TestBool);
list.Add(TestInt);

for(int i = 0; i < list.Count; i++)
{
   list[i].Value // <- what's the type of this?
}
Martinho Fernandes