I'm trying to store a list of generic objects in a generic list, but I'm having difficulty declaring it. My object looks like:
public class Field<T>
{
public string Name { get; set; }
public string Description { get; set; }
public T Value { get; set; }
/*
...
*/
}
I'd like to create a list of these. My problem is that each object in the list can have a separate type, so that the populated list could contain something like this:
{ Field<DateTime>, Field<int>, Field<double>, Field<DateTime> }
So how do I declare that?
List<Field<?>>
(I'd like to stay as typesafe as possible, so I don't want to use an ArrayList).
List<Double> now reads “ List of Double .” List is a generic interface, expressed as List<E> , that takes a Double type argument, which is also specified when creating the actual object.
The definition of generic is something without a brand name. An example of generic is the type of soap with a store's label that says "soap," but without a brand name. adjective.
This is situation where it may benefit you to have an abstract base class (or interface) containing the non-generic bits:
public abstract class Field
{
public string Name { get; set; }
public string Description { get; set; }
}
public class Field<T> : Field
{
public T Value { get; set; }
/*
...
*/
}
Then you can have a List<Field>
. That expresses all the information you actually know about the list. You don't know the types of the fields' values, as they can vary from one field to another.
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