Possible to have a List of Generic items of different types?
-
Forgive the 'generic' formatting, I don't seem to be able to post 'proper' generic code here. I have a simple class (see below). I need to have a way to have a SINGLE collection of 'GenericDataElement' objects. Is this possible? Some of the items may be
GenericDataElement<>
, while others may beGenericDataElement<>.
public class GenericDataElement<> { private string name; private T value; public string Name { get { return name; } } public T Value { get { return value; } } public GenericDataElement(string name, T value) { this.name = name; this.value = value; } }
-
Forgive the 'generic' formatting, I don't seem to be able to post 'proper' generic code here. I have a simple class (see below). I need to have a way to have a SINGLE collection of 'GenericDataElement' objects. Is this possible? Some of the items may be
GenericDataElement<>
, while others may beGenericDataElement<>.
public class GenericDataElement<> { private string name; private T value; public string Name { get { return name; } } public T Value { get { return value; } } public GenericDataElement(string name, T value) { this.name = name; this.value = value; } }
It isn't possible to have a strongly typed generic list that allows 2 different type parameters, but you can do something like that: public class GenericDataElement { } public class GenericDataElement : GenericDataElement { public GenericDataElement(string name, T value) { this.name = name; this.value = value; } private string name; public string Name { get { return name; } } private T value; public T Value { get { return value; } } } public class Test { List list = new List(); public void TestIt() { list.Add(new GenericDataElement("string", "value")); list.Add(new GenericDataElement("int", 1)); foreach (GenericDataElement gde in list) { if (gde is GenericDataElement) Console.WriteLine("int"); else Console.WriteLine("string"); } } } But you will have an untyped collection, of course. -^-^-^-^-^- no risk no funk ................... please vote ------>