Tuesday, November 27, 2007

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

1 comment:

Asghar Panahy said...

The following are equivalent:

myControl.RowCountChanged += new EventHandler(MyChangedEventHandlerMethod);

myControl.RowCountChanged += MyChangedEventHandlerMethod;

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

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