Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast delegate to Func in C#

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?

like image 374
AndreyAkinshin Avatar asked Dec 15 '09 11:12

AndreyAkinshin


People also ask

What is func delegate?

Func is a delegate that points to a method that accepts one or more arguments and returns a value. Action is a delegate that points to a method which in turn accepts one or more arguments but returns no value. In other words, you should use Action when your delegate points to a method that returns void.

How do you call a Func delegate method in C#?

Func<int, int, int> Add = Sum; This Func delegate takes two parameters and returns a single value. In the following example, we use a delegate with three input parameters. int Sum(int x, int y, int z) { return x + y + z; } Func<int, int, int, int> add = Sum; int res = add(150, 20, 30); Console.

How do you call a function using delegates?

Delegates can be invoke like a normal function or Invoke() method. Multiple methods can be assigned to the delegate using "+" or "+=" operator and removed using "-" or "-=" operator. It is called multicast delegate. If a multicast delegate returns a value then it returns the value from the last assigned target method.

What is func t TResult?

Func<T, TResult> defines a function that accepts one parameter (of type T) and returns an object (of type TResult).


1 Answers

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.

like image 135
Winston Smith Avatar answered Sep 25 '22 07:09

Winston Smith