Tuesday, March 09, 2010

Playing with Generic List

Generic List a new feature provided by .NET 2.0 and above which can be declared as follow: List<string> lstString = new List<string>();
Creating Generic Object using Reflection
Now; there is nothing now in this. And we all know that the generics are type safe. That means you can not pass Child object's referece (Without type casting) where the base class is expected. In case if you need to create Generic List object dynamically depending upon your business scenarios you can use Reflection API to create generic object.

Lets see how to do this:

public static object CreateGenericObject(Type genericType, Type innerType, params object[] args)


System.Type speType = genericType.MakeGenericType(new System.Type[] { innerType });

return Activator.CreateInstance(speType, args);


And your client code would be as follows:

object geneticListObject = CreateGenericObject(typeof(List<>),typeof(int));

Now lets see one more feature of .NET 2.0 i.e. Inline functions (anonymous methods):

Lets assume you have a generic collection of objects (lets assume student); and you want to search on Student Name starting with "K". You dont need to make another call to the server for this. Here is the code for the same:

List<Student> localStudentList = mainStudentList.FindAll(delegate(Student student)
return student.StudentName.StartsWith("K");

the above code will return the list of students (in localStudentList object) whose name starts with K.To extends this you can write various AND and OR conditions. Isn't this good?

Kaushal Patel
Contact Me Twitter