Thursday, January 3, 2008

C# on the journey to functional programming

From old-school imperative...
var list = new List<int>(){1, 2, 3};
int sum = 0;
foreach (int n in list)
{
   sum += n;
}
Assert.AreEqual(6, sum);
...over clumsy delegate...
var list = new List<int>(){1, 2, 3};
int sum = 0;
list.ForEach(delegate(int number) { sum += number; });
Assert.AreEqual(6, sum);
...to sexy lambda.
var list = new List<int>(){1, 2, 3};
int sum = 0;
list.ForEach(number => sum += number);
Assert.AreEqual(6, sum);

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...