Multi-Line Lambdas in C# and VB.NET






4.69/5 (11 votes)
Lambdas can be composed of multiple lines of code.
Thanks to a recent answer on CodeProject, I discovered that lambdas can be made using multiple lines of code (I always assumed they could only use a single line of code). Here is how it's done in C#:
Action<int, int> dialog = (int1, int2) =>
{
MessageBox.Show(int1.ToString());
MessageBox.Show(int2.ToString());
};
dialog(1, 2);
The key there is to use curly braces to create a code block to contain multiple lines. After some Google searching, I found that this can be done in VB.NET as well:
Dim dialog As Action(Of Integer, Integer) =
Sub(int1, int2)
MessageBox.Show(int1.ToString())
MessageBox.Show(int2.ToString())
End Sub
dialog(1, 2)
The key there is to add "End Sub
" (or "End Function
") and place each statement on a new line.