I am wondering if this is possible, what I want to do is set the type of list when I create an instance of this class.
class MyClass
{
private Type _type = typeof(string);
public MyClass(Type type)
{
this._type = type;
}
public List<_type> MyList { get; set; } <----it does not like this
}
Use a generic type definition:
class MyClass<T>
{
private Type _type = typeof(string);
public MyClass()
{
this._type = typeof(T);
}
public List<T> MyList { get; set; } <----it likes this
}
If you need to accept a passed in Type argument and generics won't work, you can do something like:
class MyClass
{
private Type _type = typeof(string);
public MyClass(Type type)
{
this._type = typeof(type);
this.MyList = Activator.CreateInstance(typeof(List<>).MakeGenericType(type));
}
public IList MyList { get; set; } <----it likes this
}
The advantage is it enforces the type constraint on the list. Only items of the given type can be added to the list. The downside is you need to cast every item you get from it. It would be better if you avoided this sort of thing and used the generic example above. A third option is to elide generics entirely:
class MyClass
{
private Type _type = typeof(string);
public MyClass(Type type)
{
this._type = typeof(type);
this.MyList = new ArrayList();
}
public IList MyList { get; set; } <----it likes this
}
This doesn't provide any type enforcement. Your mileage may vary.
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