In this tutorial, we are going to learn Anonymous method in C#. Anonymous methods are methods that have the only body without method name. Let’s discuss Anonymous method with the example.

After Completing this tutorial you will be able to understand:

  • What is Anonymous Method in C#
  • How to use Anonymous Method in C#.

Introduction:

As the name sounds Anonymous methods are the methods without a name with the just body. The Anonymous method allows us to pass a block of code as a Delegate parameter. Anonymous methods are methods that have the only body without a name and with optional parameters and return type. Anonymous methods are created using delegate keyword.

Point to remember about Anonymous Methods:

  • Anonymous Method can be defined using Delegate keyword.
  • An Anonymous method can access the variables and functions outside the anonymous method.
  • Variables declared inside the Anonymous methods can’t be accessed outside the Anonymous method.
  • The Anonymous method does not allow the use of goto, break or continue statements.
  • An Anonymous method cannot access ref or out parameter of an outer method.
  • We cannot access unsafe code within the Anonymous method.

The example of Anonymous Method in C#:

Create a Console Application called AnonymousMethodDemo.

Anonymous Method

Open Program.cs file and write the following code.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;



namespace AnonymousMethodDemo
{
public delegate void Calculator(int iFirstNumber,int iSecondNumber);
class Program
{
static void Main(string[] args)
{
Calculator objAddition = delegate(int iFirstNumber, int iSecondNumber)
{
Console.WriteLine("Addition of Two Number {0}", iFirstNumber + iSecondNumber);
};
objAddition(15, 5);
Calculator objSubtraction = delegate(int iFirstNumber, int iSecondNumber)
{
Console.WriteLine("Subtraction of Two Number {0}", iFirstNumber - iSecondNumber);
};
objSubtraction(15, 5);



Calculator objMultiplication = delegate(int iFirstNumber, int iSecondNumber)
{
Console.WriteLine("Multiplication of Two Number {0}", iFirstNumber * iSecondNumber);
};
objMultiplication(15, 5);



Calculator objDivision = delegate(int iFirstNumber, int iSecondNumber)
{
Console.WriteLine("Division of Two Number {0}", iFirstNumber / iSecondNumber);
};
objDivision(15, 5);
Console.ReadKey();
}
}
}

You can see from the above code that we have declared an Anonymous method like this:

Calculator objAddition = delegate(int iFirstNumber, int iSecondNumber)
{
Console.WriteLine(“Addition of Two Number {0}”, iFirstNumber + iSecondNumber);
};

Run the application and look over the output window.

Anonymous Method

Conclusion:

I hope you understand this tutorial through out clearly. I would like to have your Feedback, Comments and Suggestions.

View More:

Thank You,

Leave a Comment