mercredi 24 juillet 2019

Why does Activator.CreateInstance() for a Generic List Produce a Non-Matching Type?

The following code example is just for illustration purposes. I realize its not practical, but my practical use case is much more complex. I'm trying to keep it simple for demonstration.

Assume that the passed in argument "collection" contains a List of System.String.

public dynamic DoopList(dynamic collection)
{
   Type collectionType = collection.GetType();

   Type[] args = iCollection.GetGenericArguments();

   Type listType = typeof(List<>).MakeGenericType(genericArg);

   if(collectionType == listType)
       return Activator.CreateInstance(listType);
   else
       return null;
}

Now I would THINK that DoopList would return exactly the same Type as collection. Instead, you get a slightly different type because Activator.CreateInstance() returns a slight variation.

When I pass in a collection of type: System.Collections.Generic.List`1[System.String]

...the if condition evaluates to true, and the function returns an object of type: System.Collections.Generic.List<String>

Well that's a problem, because then I can't assign the result to another variable that expects System.Collections.Generic.List`1[System.String].

I'm pretty sure what's going on here has something to do with nature of generics, but I really don't understand it.

What is the difference between Generic.List`1[System.String] and Generic.List<string>?

And more importantly, why does Activator.CreateInstance() create a Generic.List<string> instead of a Generic.List`1[System.String] and how do I fix the problem so I can get the same type as the input collection?





Aucun commentaire:

Enregistrer un commentaire