Click here to Skip to main content
15,885,914 members
Articles / Programming Languages / Visual Basic
Tip/Trick

Multi-Line Lambdas in C# and VB.NET

Rate me:
Please Sign up or sign in to vote.
4.69/5 (11 votes)
2 Feb 2011CPOL 37.7K   8   1
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)


Written By
Web Developer
United States United States

  • Managing Your JavaScript Library in ASP.NET (if you work with ASP.net and you don't read that, you are dead to me).
  • Graduated summa cum laude with a BS in Computer Science.
  • Wrote some articles and some tips.
  • DDR ("New high score? What does that mean? Did I break it?"), ping pong, and volleyball enthusiast.
  • Software I have donated to (you should too):

Comments and Discussions

 
GeneralReason for my vote of 5 very good to put code for C# AND VB Pin
dg784-Feb-11 21:44
professionaldg784-Feb-11 21:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.