Skip to content

Anonymous Methods C#

Last time we talked about Delegates, now we’ll look into the concept of anonymous methods that truly shines with the use of delegates.

The Delegate ‘Clutter’

In order to use a Delegate you must do 4 things:

/*1. Declare the delegate*/
public delegate int ProcessTwoNumbersDelegate(int a, int b);
/*2. Define a variable of the delegate type we declared*/
public ProcessTwoNumbersDelegate processNumbers;
/*3. Assign a named method to the delegate*/
_weirdCalculator.processNumbersDelegate = Calculator.Subtract;
/*4. Use the delegate - pass the delegate as parameter to a method*/
_weirdCalculator.processNumbersDelegate(a, b);
//----------------------------------------
private string ProcessNumbersWithMsg(int a, int b, ProcessTwoNumbersDelegate processNumbersDelegate)
{
  if (processNumbersDelegate == null)
    return "Press Add/Subtract first!";

  return "Weird msg! " + processNumbersDelegate(a, b);
}

Anonymous Methods at work

By using anonymous methods, we could change step 3 and assign a method ‘on the fly’ without creating a new one

_weirdCalculator.processNumbersDelegate = delegate(int x, int y)
{
  return x * y;
};

The code can be simplified even more

_weirdCalculator.processNumbersDelegate = (x, y) => x * y;

Keep in mind that if you have break/continue statements inside your anonymous method the target should remain inside the code block!
If you want more information about the scope of the paramters you can check the official microsoft docs.

Summary

And that’s pretty much it!
When using anonymous methods, you reduce a little bit of coding overhead since you do not have to create a new named method. There is not much else to
say here so if you want to experiment a little bit more clone or download a full working example from Github.

Finally you can always Buy me a coffeeBuy me a coffee and help me stay awake to continue my excavations!

2

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *