Different Generics T in the same collection
c#, generics
Solution
In order to be stored in a `List<T>` together the columns must have a common base type. The closest common base class of `DateColumn` and `NumberColumn` is `object`. Neither derives from `Column<T>` but instead a specific and different instantiation of `Column<T>`.
One solution here is to introduce a non-generic `Column` type which `Column<T>` derives from and store that in the `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());
Problem
``` 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 I have is adding these into a generic collection. I know its possible but how can I store multiple types in a collection etc ``` IList<Column<?>> columns = new List<Column<?>() ``` I would really appreciate any advice on achieving this goal. The goal being having different column types stored in the same List. Its worth mentioning I am using NHibernate and the discriminator to load the appropriate object.Ultimately the Value needs to have the type of the class. Many thanks for your help in advance.