Reputation: 4375
I am trying to create a custom class like this as follows.
public MyClass<T>
{
public string Value1 { get; set; }
public T Value2 { get; set; }
public string Value3 { get; set; }
}
The value of T could be either string or int or datetime .I assume i can create new instance of this class like
MyClass<int> intclass = new MyClass<int>();
MyClass<String> stringclass=new MyClass<String>();
and so forth.
Is it possible to create a collection of the above classes where i can put intclass and stringclass into a custom collection.
Upvotes: 2
Views: 110
Reputation: 23198
If you want to mix different generic types (so have a collection containing both MyClass<int>
and MyClass<string>
) you need to define some common base type or use a collection that is not strongly typed:
public class MyClass<T> : MyClass
{
public T Value2 { get; set; }
}
public class MyClass
{
public string Value1 { get; set; }
public string Value3 { get; set; }
}
Then you can define a collection like:
List<MyClass> list = new List<MyClass>();
list.Add(new MyClass<int>());
list.Add(new MyClass<string>());
You will have to cast results when retrieving entries in order to access their Value2
property though.
Another option to avoid the base-class is simply to use a List<object>
:
List<object> list = new List<object>();
list.Add(new MyClass<int>());
list.Add(new MyClass<string>());
But it's the same problem as above, but plausibly worse (because then you can store anything in there)
EDIT: There are various ways of how to allow untyped access to Value2
in the base non-generic MyClass
. One way is to define an "untyped" version of it on the base class and override it on the subclass which would perform type-checking:
public abstract class MyClass
{
public string Value1 { get; set; }
public abstract object Value2Untyped { get; set; }
public string Value3 { get; set; }
}
public class MyClass<T> : MyClass
{
public T Value2 { get; set; }
public override object Value2Untyped
{
get
{
return Value2;
}
set
{
Value2 = (T)value;
}
}
}
Then for all your objects or collections that are typed against the base non-generic MyClass
, you can still access values, and even set values at runtime. (the set
of course is optional)
Upvotes: 5
Reputation: 2644
you mean something like this?
List<MyClass<int>> intClassList = new List<MyClass<int>>();
intClassList.Add(new MyClass<int>());
Upvotes: 0