Question

when i run the program an error message pops up, it says: Object reference not set to an instance of an object from the methodinfo.invoke(data, null). what i want is create a dynamic generic collection in run time, depends on the xml file, it can be list<classname>, dictionary<string, classname>, customgenericlist<T>, etc.

Below are the codes: using list as a test subject.

  data = InstantiateGeneric("System.Collections.Generic.List`1", "System.String");
            anobj = Type.GetType("System.Collections.Generic.List`1").MakeGenericType(Type.GetType("System.String"));
            MethodInfo mymethodinfo = anobj.GetMethod("Count");
            Console.WriteLine(mymethodinfo.Invoke(data, null));

this is the code to instantiate the said datatype:

 public object InstantiateGeneric(string namespaceName_className, string generic_namespaceName_className)
        {
            Type genericType = Type.GetType(namespaceName_className);
            Type[] typeArgs = {Type.GetType(generic_namespaceName_className)};
            Type obj = genericType.MakeGenericType(typeArgs);
            return Activator.CreateInstance(obj);
        }
Was it helpful?

Solution

Count is a property, not a method:

var prop = anobj.GetProperty("Count");
Console.WriteLine(prop.GetValue(data, null));

However, it would be better to cast to the non-generic IList:

var data = (IList)InstantiateGeneric("System.Collections.Generic.List`1",
                                     "System.String");
Console.WriteLine(data.Count);

I also suggest talking in terms of Type, not magic strings:

var itemType = typeof(string); // from somewhere, perhaps external
var listType = typeof(List<>).MakeGenericType(itemType);
var data = (IList)Activator.CreateInstance(listType);
Console.WriteLine(data.Count);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top