Skip to content

Instantly share code, notes, and snippets.

@mirasrael
Created November 9, 2018 09:51
Show Gist options
  • Save mirasrael/c3f68cb873b0dbc19abc29c6e1e924f7 to your computer and use it in GitHub Desktop.
Save mirasrael/c3f68cb873b0dbc19abc29c6e1e924f7 to your computer and use it in GitHub Desktop.
CreateConstructor expression for C#
using System;
using System.Linq.Expressions;
public class ExpressionUtils
{
public static Func<TParam, TType> CreateConstructor<TType, TParam>()
{
var type = typeof(TType);
// Get the constructor info for these parameters
var constructorInfo = type.GetConstructor(new[] { typeof(TParam) });
if (constructorInfo == null)
throw new MissingMethodException($"Constructor with type {typeof(TParam)} wasn't found for {typeof(TType)}");
// define a T1 parameter
var paramExpr = Expression.Parameter(typeof(TParam));
// just call the constructor.
var body = Expression.New(constructorInfo, paramExpr);
var constructor = Expression.Lambda<Func<TParam, TType>>(body, paramExpr);
return constructor.Compile();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment