Use Anonymous Method with a Delegate in C#

A colleague of mine asked me a question - ‘How can we use an Anonymous method with a Delegate and when should we do it”.

By using anonymous methods, you reduce the coding overhead in instantiating delegates, by eliminating the need to create a separate method. You can use it to run code snippets that would otherwise require a named method or use it as a quick event-handler with no name.

Here’s the code that shows how to do it. Comments have been placed inline to understand the code

namespace ConsoleApplication2
{
// Define a Delegate
delegate int AddThenMultiply(int i, int j);

class Class1
{
static void Main(string[] args)
{
// Instatiate delegate type using anonymous method
AddThenMultiply atm = delegate(int i, int j)
{
return (i + j) * 2;
};

// Anonymous delegate call
int result = atm(2, 3);
Console.WriteLine("Result is: " + result);
Console.ReadLine();
}

}
}

OUTPUT

Anonymous Method Delegate Call






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

2 comments:

Navsingh from Financial Technology said...

Thanks for the wonderful article from this I understood that

Lambda expressions is a wrapper on Anonymous Methods which inturn a wrapper on delegates.

Delegates is used to just specify a method in some constant memory location & can be called from any where using the delegate.

Please correct me if Iam wrong

Suprotim Agarwal said...

Navsingh: yes that's correct