Different T generics in one collection

public abstract Column<T> { private T Value {get;set;} public abstract string Format(); } public class DateColumn : Column<DateTime> { public override string Format() { return Value.ToString("dd-MMM-yyyy"); } } public class NumberColumn : Column<decimal> { public override string Format() { return Value.ToString(); } } 

The problem is to add them to the general collection. I know this is possible, but how can I store several types in a collection, etc.

 IList<Column<?>> columns = new List<Column<?>() 

I would really appreciate any advice on achieving this. The goal is to have different types of columns stored in the same list. It is worth mentioning that I use NHibernate and the discriminator to load the corresponding object. Ultimately, the value must be of the class type.

Thanks so much for your help in advance.

+7
source share
3 answers

To be stored in a List<T> together, the columns must have a common base type. The closest common base class for DateColumn and NumberColumn is object . None of them are the result of Column<T> , but instead, a concrete and different instance of Column<T> .

One solution here is to introduce a non-generic Column type from which Column<T> is inferred and stored, which is in List

 public abstract class Column { public abstract object ValueUntyped { get; } } public abstract class Column<T> : Column { public T Value { get; set; } public override object ValueUntyped { get { return Value; } } } ... IList<Column> list = new List<Column>(); list.Add(new DateColumn()); list.Add(new NumberColumn()); 
+13
source

It probably makes sense to deduce from a non-generic Column set that wraps as much as possible a non-generic column interface ... then declares your list as a List<Column> .

+3
source

General information refers to the type indication. If you want to use dynamic types, use the classic ArrayList instead.

+2
source

All Articles