Cast delegate to Func in C#

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.


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

Try this:

Func<int, int> c = (Func<int, int>)Delegate.CreateDelegate(typeof(Func<int, int>), 
                                                           b.Target,
                                                           b.Method);

The problem is that:

SomeDelegate a = Inc;

Isn't actually a cast. It's the short-form of:

SomeDelegate a = new SomeDelegate(Inc);

Therefore there's no cast. A simple solution to your problem can be this (in C# 3.0)

Func<int,int> f = i=>a(i);