Home > Net >  Can't instantiate and populate a list object from Type
Can't instantiate and populate a list object from Type

Time:02-10

I am trying to create a method which will take a Type parameter, will check to see if it is a List type, and if so it will instantiate a list, populate it with two instances of the value parameter, and return it.

This is the code that I am working with right now.

Type type = typeof(List<string>);
object value = "stuff";

List<string> myList = CreateAStringList(type, value) as List<string>;

private object CreateAStringList(Type type, object value)
{
    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
    {
        var constructedListType = typeof(List<>).MakeGenericType(type);
        var instance = Activator.CreateInstance(constructedListType);
        IList outList = (IList)instance;

        outList.Add(value);
        outList.Add(value);

        return outList;
    }
    return null;
}

When it hits the outList.Add(value), I get this error.

System.ArgumentException: 'The value "stuff" is not of type "System.Collections.Generic.List`1[System.String]" and cannot be used in this generic collection.

Can anyone tell me how I need to massage outList, or this method, to get what I need?

CodePudding user response:

  •  Tags:  
  • Related