1

I am writing delegates as like this.

  delegate void MyMethod(string arg1, string arg2);
  MyMethod mm;

I don't know why it needs two lines to declare a single delegate. If my class has 20 delegates, I need to write 40 line of code. Can anybody tell me a way to write this in one line of code ? Thanks in Advance.

Yesudass Moses
  • 1,841
  • 3
  • 27
  • 63
  • 3
    If you use .NET Framework 3.5 or later you can use [Func](http://msdn.microsoft.com/en-us/library/bb549151(v=vs.90).aspx) and [Avtion](http://msdn.microsoft.com/en-us/library/018hxwa8(v=vs.110).aspx) delegates, instead of declaring new delegate type each time. – Yurii Jun 23 '14 at 06:12
  • Is there any perfomance difference between Func and Delegate ? – Yesudass Moses Jun 23 '14 at 06:18
  • This - [c# generic vs not-generic performance](http://stackoverflow.com/questions/17307326/c-sharp-generic-vs-not-generic-performance), should help. – Yurii Jun 23 '14 at 06:25

1 Answers1

10

You're declaring two very different things here:

  • The first line declares a delegate type called MyMethod
  • The second line declares a field of that delegate type

It's important to understand the difference, because then you can work out when you really want to declare a new delegate type and when you just want to declare a field of an existing delegate type. If your class has 20 delegate fields, you almost certainly don't want to declare a new type for each of them. If they've got the same signature, you could use a single type... or better, just use one of the framework types such as Action<...> or Func<...>.

Action<string, string> mm;

(There are Action delegates for void return types, and Func delegates for non-void return types, with different numbers of parameters, all expressed generically. Look at MSDN for more details.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194