Anonymous Functions
An anonymous function is an "inline" statement or expression that can be used wherever a delegate
type is expected. You can use it to initialize a named delegate or pass it instead of a named delegate
type as a method parameter.
There are two kinds of anonymous functions;
1. Anonymous Methods
2. Lambda Expressions
1. Anonymous methods
Anonymous methods provide a technique to pass a code block as a delegate parameter.
Anonymous methods are basically methods without a name, just the body.
You need not specify the return type in an anonymous method;
// Create a handler for a click event.
button1.Click += delegate(System.Object o, System.EventArgs e)
{ System.Windows.Forms.MessageBox.Show("Click!"); };
2. Lambda expressions
A lambda expression is an anonymous function that can contain expressions and statements, and can be
used to create delegates or expression tree types.
class Program
{
static void Main(string[] args)
{
new ShoppingCart().Process(delegate(bool x) { return x ? 10 : 5; }
);
}
}
Anonymous Types
Anonymous types provide a convenient way to encapsulate a set of read-only properties into a
single object without having to explicitly define a type first. The type name is generated by the
compiler and is not available at the source code level. The type of each property is inferred by the
compiler.
You create anonymous types by using the new operator together with an object initializer.
var productQuery = from prod in products
select new { prod.Color, prod.Price };
foreach (var v in productQuery)
{
Console.WriteLine("Color={0}, Price={1}", v.Color, v.Price);
}