Sunday, June 10, 2012

Avoid stringly-typed, do the .NET proper, use strongly-typed

When you want to do this during run-time...
System.Collections.Generic.IList<Product> products = new System.Collections.Generic.List<Product>();



...instead of doing this:

...
Type elemType = ...
IList clonedList = (IList)Common.Create("System.Collections.Generic.List", elemType);
...

static class Common
{
    internal static object Create(string name, params Type[] types)
    {
        string t = name + "`" + types.Length;
        Type generic = Type.GetType(t).MakeGenericType(types);
        return Activator.CreateInstance(generic);
    }
}


Do this:
Type elemType = ...
IList clonedList = (IList) Activator.CreateInstance(typeof(System.Collections.Generic.List<>).MakeGenericType(elemType));




Happy Coding! ツ

No comments:

Post a Comment