Skip to content

Instantly share code, notes, and snippets.

@SteveDunn
Created July 30, 2021 21:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SteveDunn/671cffb177ad9793fa0e37568efef39a to your computer and use it in GitHub Desktop.
Save SteveDunn/671cffb177ad9793fa0e37568efef39a to your computer and use it in GitHub Desktop.
Workaround for inability to create C# generic constraints for the presence of a constructor that takes parameters... i.e. Foo<T>(string name) where T: new(string)
public Func<T1, TResult> CompileConstructor<T1, TResult>()
{
var type1 = typeof(T1);
var parameter1 = Expression.Parameter(type1);
var constructor = typeof(TResult).GetConstructor(new Type[] { type1 });
var body = Expression.New(constructor, parameter1);
var lambda = Expression.Lambda<Func<T1, TResult>>(body, parameter1);
var method = lambda.Compile();
return method;
}
// obviously you could do some caching here...
public TResult New<T1, TResult>(T1 t1)
{
return GetConstructor<T1, TResult>()(t1);
}
// example usage: i.e. a generic method that calls an unnamed type constructor that takes a parameter (in this case a string).
public TResult CreateNode<TResult>(string name) where TResult: INode
{
return New<TResult,string>(name);
}
// copied line by line from https://gist.github.com/adjames/1736161 - in case it goes and I can't remember how to do it!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment