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



Anonymous Method Delegate Call

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal


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