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.
Generics are similar to collections, but implemented using Type parameters. Generic collections accept a type parameter and accept the elements of only those type for which the generic collection is instantiated. These enforce strict type checks.
It is prohibited that a type implements or extends two different instantiations of the same interface. This is because the bridge method generation process cannot handle this situation.
A generic collection is strongly typed (you can store one type of objects into it) so that we can eliminate runtime type mismatches, it improves the performance by avoiding boxing and unboxing.
A Generic collection is a class that provides type safety without having to derive from a base collection type and implement type-specific members. A Non-generic collection is a specialized class for data storage and retrieval that provides support for stacks, queues, lists and hash tables.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With