We have the variable "object value" , which points to a list with one of any type. For example, you can refer to such objects: List<string> or List<Cat> . Which one of them we do not know.
Question: how to create a list of the type we need?
PS1: Googled - to no avail.
PS2: I wrote this code:

  Type valueType = value.GetType(); Type listType = valueType.GetGenericArguments()[0]; List<object> instanceList = (List<object>) Activator.CreateInstance(valueType); 

As a result, a type conversion error is "InvalidCastException" - "InvalidCastException" .

  • one
    try var instanceList = Activator.CreateInstance(valueType); and see what type instanceList - Specter
  • At instanceList that is necessary. - uzumaxy

2 answers 2

List <cat> is not cast to List <object>. I recommend reading about covariance.

If you are working in 4th and higher, it is possible for IEnumerable <t>, but no more.

Plus, in all versions of dotnet, starting from the 2nd, covariance is supported for arrays.

In addition, instead of List <object> you can use IList, since List <t> implements this interface. This is the best solution if you need a list for working in weakly typed scenarios.

  • Thank you, I will read. <br/> Another small question: if I try to refer to the contents of "value" using the IList interface, I get a compilation error, because the interface requires a class with its implementation, and at the time of writing the program it is clearly stated that the object under the reference "value" is treated as the type object (although in fact it points to a List object <some type>). Roughly speaking, I need to write a trace. code: <pre> <code> Type valueType = value.GetType (); IList <valueType> instanceList = (List <valueType>) value; / * the problem is that there will be an error * / </ code> </ pre> - uzumaxy
  • one
    Not IList<valuetype> , but IList . Namespace System.Collections . - Modus

In c # there is a dynamic type that allows me to solve my problem. You just had to write:

 dynamic instanceList=value; 

And then it was possible to work with him as with a list. Thanks to everyone who replied to the topic. Most likely, I have not fully and correctly described the question, so sorry.