Created
November 9, 2018 09:51
-
-
Save mirasrael/c3f68cb873b0dbc19abc29c6e1e924f7 to your computer and use it in GitHub Desktop.
CreateConstructor expression for C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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