Make Generic Type

I been working with .Net for a number of years now, and the more I work with, the more genric my code is getting. Building a generic object parser has been something I have spent a lot of time on.

Back in the days of data sets, moving data from a dataset to an object model representing data model has been a constant pain point. You would think they would have this problem nailed by now. But this is still the place you spend a lot of time. If it's not trying to build some kind of generic parser to make life easier, then it's trying to figure out how the latest Mirosoft or open source parser/mapper/ORM works, and 90% of that time is spent trying to figure out why it's not working in your specific case.

One of the constrant road block i have encountered during my many attempts to build a custom parser has been to create a generic list of type T. Mapping simple object types is easy using reflection. But once you get to a child element you need to create a generic list of type T. But you have no way of knowing what T will be, (Something important to note is that T is different to .GetType() or typeof()) so often resort to using some clumsy way of finding what the generic type is, then using MakeGenericType() method to build a generic List of Type T.

This almost always takes ages to look up and find the technique to use, and when it's finished everything is hunky dory until you hit some performance issues.

In looking for alternatives to build these generic types I found a really simple 3 line method to create a generic list.

string s = typeof(foo).FullName;
s= "System.Collections.Generic.List'1[[" + s + "]]";
System.Collections.IList fl = Activator.CreateInstance(Type.GetType(s)) as System.Collections.IList;


So all you need to do is have the full string name of you generic type, and we know what the generic list type is, and then we use the activator to create an instance from a string concatination. This is much easier to build object with strings because you dont need to know what T is, and you can get the type name from the GetType().FullName property.

Easy as pie!!

I haven't checked to see what the performance hit would be, but it would be interesting to see if there are any improvements over MakeGenericType().

Comments

Popular posts from this blog

What good looks like!!

A microservice journey - part 2: what type of micro service are you?

Validation Rules