I have the following method:
public void SetList<T>(IList<T> listINeedToStore)
{
//Store the list in instance level scope
}
I would like to take the listINeedToStore
parameter and store it in a private variable but I have failed to find a way. I tried to do something like private IList<object> _tempVariable;
and then set _tempVariable
to the listINeedToStore
variable so I can use it later to remove or add items to it. I would set the list like _tempVariable = (IList<object>)listINeedToStore;
. This does not work and will not compile. Something I should note is that T is a type of Enum.
I am sure there is a way to do this but I do not know it.
Thanks,
You can't do it in a generic way without making the type generic instead of the method, basically. You can store the reference, but it would have to be via a field of a non-generic type, e.g. IEnumerable
or even just object
. To really use the list, you'd have to fetch it again with a generic method, and cast. For example:
private object list;
public void SetList<T>(IList<T> list)
{
this.list = list;
}
public List<T> GetList<T>()
{
return (List<T>) list;
}
The fetch will fail at execution time if you specify the wrong type argument, of course.
I'd try to avoid this design if possible, but if you really need to do it, it will work. It just adds the burden of getting the type right to all the callers.
Note that if you change the parameter from IList<T>
to List<T>
, you could then store it in an IList
(non-generic) which could be slightly more useful - but which would restrict the circumstances in which you could call the method, of course.
See more on this question at Stackoverflow