Thursday, August 26, 2010

C#: From delegates to anonymous methods to lambda expressions to Func delegates

Let's have a look at how the delegate syntax have evolved since the very first version of the .NET Framework and the C# language until today:
1. Basic delegates, .NET 1.0:

delegate int Add(int number1, int number2);

public int AddNumbers(int number1, int number2)
{
 return number1 + number2;
}

[TestMethod]
public void TestAddNumbers()
{
 var add = new Add(AddNumbers);

 Assert.AreEqual(4, add(1, 3));
}
2. Anonymous methods, .NET 2.0:

delegate int Add(int number1, int number2);

[TestMethod]
public void TestAddNumbers()
{
 Add add = delegate(int number1, int number2)
   {
    return number1 + number2;
   };
   
 Assert.AreEqual(4, add(1, 3));
}
3. Lambda expressions, .NET 3.5:

delegate int Add(int number1, int number2);

[TestMethod]
public void TestAddNumbers()
{
 Add add = (number1, number2) => number1 + number2;

 Assert.AreEqual(4, add(1, 3));
}
4. Func<> delegates, .NET 3.5:

[TestMethod]
public void TestAddNumbers()
{
 Func add = (number1, number2) => number1 + number2;

 Assert.AreEqual(4, add(1, 3));
}
Published: 25.08.2010