Cast delegate to Func in C#

AndreyAkinshin picture AndreyAkinshin · Dec 15, 2009 · Viewed 23.4k times · Source

I have code:

public delegate int SomeDelegate(int p);

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

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

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

but I can't cast Inc to SomeDelegate and after that cast to Func<int, int> with usual way like this:

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

How I can do it?

Answer

Winston Smith picture Winston Smith · Dec 15, 2009

There's a much simpler way to do it, which all the other answers have missed:

Func<int, int> c = a.Invoke; 

See this blog post for more info.