Anonymous methods allow us to create delegate methods inline.

What does that mean?

Let’s create a simple delegate whose role is to sum two numbers:

Would not it be nice if we could get rid of the SumTwoNumber method and just write it’s content while we instantiate delegate ? Yes it would and we can do it! Steps are:

  1. While instantiating your delegate, remove new… part.
  2. Write delegate keyword followed by input parameter in round brackets.
  3. Type your code inside curly brackets.

What we essentially did is we created a method without method name and thus we created anonymous method. Don’t believe me? Look again at the same code that has been reformatted a bit:

When you mentioned we can write delegate methods inline, does that mean we can write methods in one line only?

No, you can write as many lines as you want. Notice semicolon (;) on line 12, you can write additional code below. But beware of that feature, because if you write too many lines whole purpose of anonymous methods disappears and that is readability. Generally you would like to keep it to 1-3 lines, more than that would best be very good candidate for standalone method.

How do i know which parameters and return types to use wile writing an anonymous methods?

Your delegate tells you that information. In our example SumTwoNumberDelegate delegate expects return type int and two int input parameters, so that is what we provided him within anonymous method.

Anonymous methods are awesome! Are there any drawbacks to using them?

You would normally use delegate, instead of method, if you do not intend to use a function multiple times. On the other hand it makes no sense to write same anonymous method multiple times if you can reuse one method + it is easier to maintain that one method than multiple anonymous methods.

Can i make my code even simpler?

Yes you can, by using lambda expressions!