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
Tweet
2 comments:
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
Navsingh: yes that's correct
Post a Comment