Creating A Generic List At Runtime

By Anoop Madhusudanan

Vote on HN


About Back To Basics - It's often good to look back and fill any gaps we might be having, in certain aspects of the language or framework we use. I'll be examining and blogging about some well known features of C# and .NET, in Back To Basics series - Probably in a bit more detail.





How to create a generic list of members of typeX, where typeX is unknown at the time of writing the code?

Normal Scenario

In C#, it is pretty easy to use generic lists and collections. For example, we can declare a string list like
List<string> strList=new List<string>();
And later, we can invoke the methods in strList to add or remove elements. Pretty straight forward, right?

Generic List At Runtime

Now, what if you need to create a generic list at runtime? Precisely, we want to do something like this.
List<typeX> strList=new List<typeX>();
But the catch is, at the time of writing the code, we don't really know what type is typeX. For this, we need to create a generic list at run time, which can hold members of type typeX.
Here is a small method you can use to create a generic list at runtime, which can hold members of typeX
  
        /// Creating a generic list at runtime
      private Object CreateGenericList(Type typeX)
        {
            Type listType = typeof(List<>);
            Type[] typeArgs = {typeX};   
            Type genericType = listType.MakeGenericType(typeArgs);   
            object o = Activator.CreateInstance(genericType);
            return o;
        }

Invoking methods of your list

You can use the above method to create a generic list during run time, which can hold the members of type typeX.
     //Get your type from somewhere
     Type typeX= yourObject.GetType();

     //Create a generic list which can hold members of type typeX
     object  objList =  CreateGenericList(typeX);
Now, how to invoke the methods in your list? You can use reflection to obtain the MethodInfo, and to invoke the methods dynamically.
     //Obtain method info to the Add method of our generic list
     MethodInfo mListAdd = objList.GetType().GetMethod("Add");

     //Obtain method info to the ToArray method of our generic list
     MethodInfo mListToArray = objList.GetType().GetMethod("ToArray"); 
You may obtain MethodInfos for other methods too. Now, if you want to add an item to the generic list you created, you can do something like
     //Get the type
     Type typeX=yourObject.GetType();

     //Create an object of this type
     object newItem = Activator.CreateInstance(typeX);

     //Add it to the list objList
     mListAdd.Invoke(objList, new object[] { newItem });
where 'newItem' is an object of typeX.
Similarly, if you want to create a typed array from the elements of your generic list, you can do something like
//Invoke the ToArray mothod of our generic List 'objList'
System.Array arr=(System.Array) mListToArray.Invoke(objList,null),null);

1 comment:

  1. This is awesome, thanks. You could have a return type of IList rather than Object.

    ReplyDelete

Please keep your comments clean.

© 2012. All Rights Reserved. Amazedsaint.com