65.9K
CodeProject is changing. Read more.
Home

Alternative to Activator.CreateInstance

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.67/5 (4 votes)

Jan 25, 2012

CPOL
viewsIcon

19701

Using expressions, you can achieve a faster result with less code.public static T New(){ Type t = typeof(T); Func method = Expression.Lambda>(Expression.Block(t, new Expression[] { Expression.New(t) })).Compile(); return method();}Furthermore, this can...

Using expressions, you can achieve a faster result with less code.
public static T New<T>()
{
    Type t = typeof(T);
    Func<T> method = Expression.Lambda<Func<T>>(Expression.Block(t, new Expression[] { Expression.New(t) })).Compile();

    return method();
}
Furthermore, this can be refined further by capturing the method into a dictionary and saving it off for future use. As an example, you can see this tip[^], which does something like this. From my own testing of 1000 iterations of both, mine (without caching) was 148 milliseconds, while your original was 220 milliseconds.