Search code examples
c#.netreflectiondelegateslinq-expressions

CreateDelegate Derived classes must provide an implementation


When calling creating a compiled expressiong I'm trying to call CreateDelegate on the resultant compiled delegate, but am geeting a NotSupportedException, with the explanation being: Derived classes must provide an implementation. How do I create the delegate for a compiled method?

public delegate int AddOne(int input);

void Main()
{
    var input = Expression.Parameter(typeof(int));
    var add = Expression.Add(input,Expression.Constant(1));
    var lambda = Expression.Lambda(typeof(AddOne),add,input);
    var compiled = (AddOne)lambda.Compile();
    compiled.Method.CreateDelegate(typeof(AddOne));
}

Solution

  • You don't need to call CreateDelegate. Casting the result from lambda.Compile to AddOne was all you needed.

    Observe:

    public delegate int AddOne(int input);
    
    public int Test(AddOne f)
    {
       return f(1);
    }
    
    void Main()
    {
        var input = Expression.Parameter(typeof(int));
        var add = Expression.Add(input,Expression.Constant(1));
        var lambda = Expression.Lambda(typeof(AddOne),add,input);
        var compiled = (AddOne)lambda.Compile();
        Console.WriteLine(Test(compiled)); // 2
    }
    

    You can successfully call the Test method, which accepts a delegate of type AddOne.