Convert Action<Delegate>

Given two delegates with identical signatures, you can easily convert from one to another.

delegate string d1(string x, params object[] o);
delegate string d2(string x, params object[] o);

var d2instance = new d2(d1instance);

I would like to convert Action<d1> into Action<d2>, but cannot get my head around how to do this.

class Program
{
    private delegate void d1(string x, params object[] o);
    private delegate void d2(string x, params object[] o);

    private static void DoSomething(string template, params object[] args)
    {
        Console.WriteLine(String.Format(template, args));
    }

    private static void Main(string[] args)
    {
        RunD1(m => m("Foo {0}", 42));
        RunD2(m => m("Foo {0}", 42));
    }

    private static void RunD1(Action<d1> action)
    {
        action(DoSomething);
    }

    private static void RunD2(Action<d2> action)
    {
        // This needs to call RunD1
        // RunD1(.....);
    }
}
Jon Skeet
people
quotationmark

The simplest way of creating an Action<d2> from an Action<d1> is via another lambda expression:

Action<d1> original = ...;
Action<d2> converted = x => original(new d1(x));

It would be best to avoid having the different delegate types entirely, of course :)

people

See more on this question at Stackoverflow