General collection of generic classes?

I have a class that I populate from a 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 their collection:

 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 does not seem to work. Ideas?

+4
source share
4 answers

I suspect that you really need a base class of a non-native type, otherwise there is nothing in common between the different Option<T> private types.

I understand what you are trying to do, but .NET generics do not allow you to express this relationship. This is like trying to make a map from Type instance of this type ... it just doesn't fly :(

+12
source

You must specify the type instead of the template parameter:

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

becomes

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

Adding elements of type Option<int> to the same list will not work, but this is a separate problem than what I examined above.

+7
source

String Firts, you have to say what type T is.

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

And also you cannot put this TestInt on this list ...

0
source

What you do only works with heterogeneous lists.

List<T> is a homogeneous list of type T , that is, all elements must be of type T Since Option<bool> and Option<int> have no common ancestor other than object , you cannot do this unless you use List<object> or the old ArrayList , both of which act as dissimilar lists.

Think about how to extract objects from this list:

 list.Add(TestBool); list.Add(TestInt); for(int i = 0; i < list.Count; i++) { list[i].Value // <- what the type of this? } 
0
source

All Articles