17

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;
Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
  • 11
    I think the nicest one is `MyDelegate myDeleg = myFunc.Invoke;`, from [Cast delegate to Func in C#](http://stackoverflow.com/a/1907135/7586). There is also `MyDelegate myDeleg = new MyDelegate(myFunc)` – Kobi Apr 29 '15 at 12:25

1 Answers1

17

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.

usr
  • 168,620
  • 35
  • 240
  • 369
  • Just to be explicit, that's `MyDelegate myDeleg = x => myFunc(x);` - without casting. – Kobi Apr 29 '15 at 12:19
  • Wow, I can't believe I didn't think of this. Thank you very much! – Matias Cicero Apr 29 '15 at 12:21
  • 3
    Why not just `new MyDelegate(myFunc)`? – tymtam Jul 27 '18 at 06:06
  • @tymtam does that work to convert between delegate types? I have never seen that. – usr Jul 29 '18 at 08:51
  • Yes, it should. Let's have `class A { public A(D d) { d.Invoke("I'm A!"); } public delegate object D(dynamic target); }` and `class B{ public delegate object D(dynamic target); }` and `object F(dynamic s) { Console.WriteLine(s); return null; }` and `Func f = F;`. Then you can `new A(new A.D(new B.D(f)));` – tymtam Jul 30 '18 at 00:31
  • @tymtam indeed. You should post an answer. – usr Jul 30 '18 at 08:17
  • @usr I would add an anwser, but this Q is a duplicate and I cannot :) – tymtam Jul 30 '18 at 23:57
  • @tymtam: If you merged one relevant line from your comment into your answer on the duplicate question, I would be pretty sure that you'd get many upvotes. But this long example there is nothing that a typical reader wants to see. TLDR. Keep the example, but add one main line at the very top. – Tobias Knauss Mar 03 '22 at 13:06