Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / VB

Multi-Line Lambdas in C# and VB.NET

4.69/5 (11 votes)
3 Feb 2011CPOL 38.7K  
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#:
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:
VB.NET
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)