Skip to content

Instantly share code, notes, and snippets.

@adjames
Created February 4, 2012 07:29
Show Gist options
  • Save adjames/1736161 to your computer and use it in GitHub Desktop.
Save adjames/1736161 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);
}
@dfch
Copy link

dfch commented Nov 29, 2021

@adjames, it seems that the statement return New<TResult,string>(name); should have the generics the other way round:

return New<string, TResult>(name);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment