How to convert delegate to object in C#?

13,653

Solution 1

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);
}

Solution 2

Instances of delegates are objects, so this code works (C#3 style) :

Predicate<int> p = (i)=> i >= 42;

Object[] arrayOfObject = new object[] { p };

Hope it helps !

Cédric

Solution 3

Here's an example:

class Program
{
    public delegate void TestDel();

    public static void ToInvoke(TestDel testDel)
    {
        testDel();
    }

    public static void Test()
    {
        Console.WriteLine("hello world");
    }

    static void Main(string[] args)
    {
        TestDel testDel = Program.Test;
        typeof(Program).InvokeMember(
            "ToInvoke", 
            BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static,
            null,
            null,
            new object[] { testDel });
    }
}

Solution 4

I think this blog post:

C# Reflection - Dealing with Remote Objects

answers your question perfectly.

Share:
13,653
AFgone
Author by

AFgone

Updated on June 29, 2022

Comments

  • AFgone
    AFgone almost 2 years

    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