Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert delegate to object in C#?

I am using reflection class to invoke some methods which are on the some other dll. And one of the methods' parameters are type of delegate.

And I want to invoke this methods by using reflection. So I need to pass function parameters as object array, but I could not find anything about how to convert delegate to object.

Thanks in advance

like image 927
AFgone Avatar asked Oct 20 '25 01:10

AFgone


1 Answers

A delegate is an object. Just create the expected delegate as you would normally, and pass it in the parameters array. Here is a rather contrived example:

class Mathematician {
    public delegate int MathMethod(int a, int b);

    public int DoMaths(int a, int b, MathMethod mathMethod) {
        return mathMethod(a, b);
    }
}

[Test]
public void Test() {
    var math = new Mathematician();
    Mathematician.MathMethod addition = (a, b) => a + b;
    var method = typeof(Mathematician).GetMethod("DoMaths");
    var result = method.Invoke(math, new object[] { 1, 2, addition });
    Assert.AreEqual(3, result);
}
like image 51
Matt Howells Avatar answered Oct 21 '25 14:10

Matt Howells