Anonymous Methods in C# 2.0
Provided by: Dave Juth, Senior
Systems Architect
Anonymous methods, a new feature in C#
2.0, allow you to write more concise code and avoid some of the hassles
of hooking up event handlers for trivial operations. Instead of
declaring a method that can be accessed by a delegate, you can now write
the method’s code inline.
The following example illustrates two
anonymous methods, one to sort a list of people and one to loop through
and output each member of the list:
using
System;
using
System.Collections.Generic;
using
System.Text;
namespace
AnonymousMethodsConsole
{
public
class
Program
{
static
void
Main(string[]
args)
{
List<Person>
people =
new
List<Person>();
Person
teacher =
new
Person();
teacher.LastName =
"Smith";
teacher.FirstName =
"Joe";
teacher.DOB =
new
DateTime(1959,
12, 20);
people.Add(teacher);
Person
doctor =
new
Person();
doctor.LastName =
"Williams";
doctor.FirstName =
"Mary";
doctor.DOB =
new
DateTime(1973,
5, 5);
people.Add(doctor);
Person
lawyer =
new
Person();
lawyer.LastName =
"Jones";
lawyer.FirstName =
"Tom";
lawyer.DOB =
new
DateTime(1966,
3, 15);
people.Add(lawyer);
people.Sort(delegate(Person
p1,
Person
p2) {return
Comparer<DateTime>.Default.Compare(p1.DOB,
p2.DOB);});
people.ForEach(delegate(Person
p) {
Console.WriteLine(p.FirstName
+
" "
+ p.LastName +
" "
+ p.DOB.ToShortDateString()); });
Console.ReadKey();
}
}
public
class
Person
{
public
string
LastName =
string.Empty;
public
string
FirstName =
string.Empty;
public
DateTime
DOB;
public
Person()
{
}
}
}
The first anonymous method is a custom
sort for a person’s date of birth, and it sorts the collection of people
by the DOB property:
people.Sort(delegate(Person
p1,
Person
p2) {return
Comparer<DateTime>.Default.Compare(p1.DOB,
p2.DOB);});
The second prints out the sorted
collection of people using an anonymous method instead of a typical
foreach loop.
people.ForEach(delegate(Person
p) {
Console.WriteLine(p.FirstName
+
" "
+ p.LastName +
" "
+ p.DOB.ToShortDateString()); });
Return to the tips page
|