Skip to content

Instantly share code, notes, and snippets.

@ielcoro
Created January 6, 2014 11:42
Show Gist options
  • Save ielcoro/8281644 to your computer and use it in GitHub Desktop.
Save ielcoro/8281644 to your computer and use it in GitHub Desktop.
Type Activator with Lambdas
internalstaticclass TypeActivator
{
public static Func<TBase> Create<TBase>(Type instanceType)
where TBase : class
{
Contract.Assert(instanceType != null);
NewExpression newInstanceExpression = Expression.New(instanceType);
return Expression.Lambda<Func<TBase>>(newInstanceExpression).Compile();
}
public static Func<TInstance> Create<TInstance>() where TInstance : class
{
return Create<TInstance>(typeof(TInstance));
}
public static Func<object> Create(Type instanceType)
{
Contract.Assert(instanceType != null);
return Create<object>(instanceType);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment