Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Func to Delegate [duplicate]

I have the following delegate defined:

public delegate object MyDelegate(dynamic target);

And I have a Func<dynamic, object> object:

Func<dynamic, object> myFunc

How can I convert myFunc to MyDelegate?

I have tried these instructions, none of them worked:

MyDelegate myDeleg = myFunc;
MyDelegate myDeleg = (MyDelegate) myFunc;
MyDelegate myDeleg = myFunc as MyDelegate;
like image 843
Matias Cicero Avatar asked Apr 29 '15 12:04

Matias Cicero


People also ask

What is the difference between Func and delegate?

Func is a generic delegate included in the System namespace. It has zero or more input parameters and one out parameter. The last parameter is considered as an out parameter. This delegate can point to a method that takes up to 16 Parameters and returns a value.

What is Func <> C#?

A Func in C# is a way to define a method in-line that has a return value. There is a similar concept of an Action that doesn't have a return value, but we'll get to that in a sec. The return value's type is always the last generic parameter on the Func 's definition.

How do you call a delegate function in C#?

A delegate can be declared using the delegate keyword followed by a function signature, as shown below. The following declares a delegate named MyDelegate . public delegate void MyDelegate(string msg); Above, we have declared a delegate MyDelegate with a void return type and a string parameter.

What is the advantage of using delegates in C#?

Advantages to using them in design:Allow you to develop libraries and classes that are easily extensible, since it provides an easy way to hook in other functionality (for example, a where clause in LINQ can use a delegate [Func<T,bool>] to filter on, without having to write new code in the Where method.


1 Answers

You can wrap the existing delegate:

(MyDelegate)(x => myFunc(x))

Or equivalently:

MyDelegate myDeleg = x => myFunc(x);

This causes a small performance loss on each invocation but the code is very simple.

like image 165
usr Avatar answered Oct 18 '22 14:10

usr