Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding different type of generic objects into generic list

Tags:

c#

c#-3.0

c#-4.0

Is it possible to add different type of generic objects to a list?. As below.

public class ValuePair<T>
{        
    public string Name { get; set;}
    public T Value { get; set;                     
}

and let say I have all these objects...

 ValuePair<string> data1 =  new ValuePair<string>();
 ValuePair<double> data2 =  new ValuePair<double>();
 ValuePair<int> data3 =  new ValuePair<int>();

I would like to hold these objects in a generic list.such as

List<ValuePair> list = new List<ValuePair>();

list.Add(data1);
list.Add(data2);
list.Add(data3);

Is it possible?

like image 404
Alan B Avatar asked Aug 17 '11 06:08

Alan B


People also ask

Can you instantiate a generic type?

Cannot Instantiate Generic Types with Primitive Types. Cannot Create Instances of Type Parameters. Cannot Declare Static Fields Whose Types are Type Parameters. Cannot Use Casts or instanceof With Parameterized Types.

Is it possible to inherit from a generic type?

An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.


1 Answers

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>)
like image 104
Jon Skeet Avatar answered Nov 15 '22 20:11

Jon Skeet