Anonimous Functions in C# 3.0

These parts are coming from the Language Specification document:

x => x + 1 // Implicitly typed, expression body
x => { return x + 1; } // Implicitly typed, statement body
(int x) => x + 1 // Explicitly typed, expression body
(int x) => { return x + 1; } // Explicitly typed, statement body
(x, y) => x * y // Multiple parameters
() => Console.WriteLine() // No parameters
delegate (int x) { return x + 1; } // Anonymous method expression
delegate { return 1 + 1; } // Parameter list omitted

// Example:
delegate bool Filter(int i);
void F() {
Filter f = (int n) => n < 0;
list.FindAll(f);
}

delegate void D();
void F() {
int n;
D d = () => { n = 1; };
d();

// Error, n is not definitely assigned
Console.WriteLine(n);
}

Author: Pouya Panahy

Microsoft certified DevOps engineer with passion in analysing, designing and implementing solutions for Azure Cloud with hands-on experience in security and quality assurence.

One thought on “Anonimous Functions in C# 3.0”

  1. The following are equivalent:

    myControl.RowCountChanged += new EventHandler(MyChangedEventHandlerMethod);

    myControl.RowCountChanged += MyChangedEventHandlerMethod;

    myControl.RowCountChanged += new EventHandler((sender, e) => MyChangedMethod());

    myControl.RowCountChanged += (sender, e) => MyChangedMethod();

Leave a Reply