Search This Blog

Wednesday, October 23, 2013

Anonymous Functions in C#

An anonymous function is an inline statement or expression that can be used wherever a delegate type is expected.
An anonymous function has no name.

Types of anonymous functions:
  • Lambda Expressions
  • Anonymous Methods
Example:

delegate void TestAnonymousFunctionDelegate(string s);


// A delegate can be initialized with inline code - anonymous method
TestAnonymousFunctionDelegate del1 = delegate(string s) { MessageBox.Show(s); };
del1("This is anonymous method.");

// A delegate can be initialized with a lambda expression.
TestAnonymousFunctionDelegate del2 = (x) => { MessageBox.Show(x); };
del2("This is lambda expression.");

 
<< Multicast delegates                                                                                              Events >>