Search code examples
c#.netcastingdelegates

Cast delegate to Func in C#


I have some code:

public delegate int SomeDelegate(int p);

public static int Inc(int p) {
    return p + 1;
}

I can cast Inc to SomeDelegate or to Func<int, int>:

SomeDelegate a = Inc;
Func<int, int> b = Inc;

but I can't cast SomeDelegate to Func<int, int> like this:

Func<int, int> c = (Func<int, int>)a; // Сompilation error

How I can do it?


Solution

  • SomeDelegate a = Inc;
    Func<int, int> b = Inc;
    

    is short for

    SomeDelegate a = new SomeDelegate(Inc); // no cast here
    Func<int, int> b = new Func<int, int>(Inc);
    

    You can't cast an instance of SomeDelegate to a Func<int, int> for the same reason you can't cast a string to a Dictionary<int, int> -- they're different types.

    This works:

    Func<int, int> c = x => a(x);
    

    which is syntactic sugar for

    class MyLambda
    {
       SomeDelegate a;
       public MyLambda(SomeDelegate a) { this.a = a; }
       public int Invoke(int x) { return this.a(x); }
    }
    
    Func<int, int> c = new Func<int, int>(new MyLambda(a).Invoke);