Write Delegates without messing up the code

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.

Jon Skeet
people
quotationmark

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

people

See more on this question at Stackoverflow