Adding different type of generic objects into generic list

In general, you’d have to either use a List<object> or create a non-generic base class, e.g.

public abstract class ValuePair
{
    public string Name { get; set;}
    public abstract object RawValue { get; }
}

public class ValuePair<T> : ValuePair
{
    public T Value { get; set; }              
    public object RawValue { get { return Value; } }
}

Then you can have a List<ValuePair>.

Now, there is one exception to this: covariant/contravariant types in C# 4. For example, you can write:

var streamSequenceList = new List<IEnumerable<Stream>>();

IEnumerable<MemoryStream> memoryStreams = null; // For simplicity
IEnumerable<NetworkStream> networkStreams = null; // For simplicity
IEnumerable<Stream> streams = null; // For simplicity

streamSequenceList.Add(memoryStreams);
streamSequenceList.Add(networkStreams);
streamSequenceList.Add(streams);

This isn’t applicable in your case because:

  • You’re using a generic class, not an interface
  • You couldn’t change it into a generic covariant interface because you’ve got T going “in” and “out” of the API
  • You’re using value types as type arguments, and those don’t work with generic variable (so an IEnumerable<int> isn’t an IEnumerable<object>)

Leave a Comment