C#-Specific Lambdas Operations

Intertech Tutorials

C#-Specific Lambdas Operations

As mentioned, C# lambda expressions currently offer more flexibility than their VB counterparts. The main reason C# lambdas are more expressive is due to the fact that C# supports anonymous methods.

Specifically, VB lambdas have the following limitations. VB lambdas can only be used if the underlying delegate points to functions, not subroutines. In other words, a Function statement must always have a return value.

Furthermore, VB lambdas can only process arguments via a single code statement. It is not possible to define a collection of code statements to process lambda arguments in VB.

C# lambda expressions can specify a set of code statements that will be used to process incoming arguments. Furthermore, the code statements do not need to return a value. Again, this is not currently possible in VB.

When your arguments are processed by multiple code statements, they are grouped within curly brackets to define their scope. Consider the following code example. Notice you are using a lambda that uses a delegate prototyped to return void and take a single string parameter. Also notice the code in bold is in fact an argument to the PrintInReverse delegate constructor.

namespace LambdaExpressionsMultipleParams
public delegate void PrintInReverse(string msg);

class Program
static void Main(string[] args)
  Console.WriteLine("***** Lambdas with Multiple Code Statements! *****\n");

  // This lambda pushes a single arg to
  // a stack of code statements.
  PrintInReverse p = new PrintInReverse(msg => {
    Console.WriteLine("Message is: {0}", msg);
    char[] chars = msg.ToCharArray();
    string strReverse = new string(chars);
    Console.WriteLine("Message reversed is: {0}", strReverse);

  p("Hello World!");


To wrap up your look at lambdas, remember the following:

LINQ uses lambdas transparently in the background when you make use of LINQ query operators. However, more complex LINQ queries may entail working with the lambda expressions directly. Be sure to consult the .NET Framework 3.5 SDK documentation for further examples of lambda expression syntax.

Copyright (c) 2008-2013. Intertech, Inc. All Rights Reserved. This information is to be used exclusively as an online learning aid. Any attempts to copy, reproduce, or use for training is strictly prohibited.