Skip to content

Lambda expressions C# 3.0readabilitynew scenarios

Create inline functions using concise `=>` arrow syntax.

Lambda expressions are blocks of code that can be used in place of a function. Depending on the type the receiver is expecting they become either a delegate (like an anonymous method C# 2.0) or an expression tree C# 3.0.

Code ​

csharp
delegate Image ImageProcessor(Image image);

Image HighContrast(Image image)
{
    Image newImage = (Image) image.Clone();
    imageLibrary.AdjustContrast(newImage);
    return newImage;
}

void Save(IEnumerable<Image> images)
{
    ImageProcessor processImage = highContrastMode
        ? (ImageProcessor)HighContrast
        : image => image;

    int idx = 1;
    foreach(var image in images)
        processImage(image).Save("Image" + idx++, ImageFormat.Jpeg);
}
csharp
delegate Image ImageProcessor(Image image);

Image HighContrast(Image image)
{
    Image newImage = (Image) image.Clone();
    imageLibrary.AdjustContrast(newImage);
    return newImage;
}

void Save(IEnumerable<Image> images)
{
    ImageProcessor processImage = highContrastMode
        ? (ImageProcessor)HighContrast
        : delegate (Image image) { return image; };

    int idx = 1;
    foreach(var image in images)
        processImage(image).Save("Image" + idx++, ImageFormat.Jpeg);
}

Notes ​

  • The current compiler puts non-capturing lambdas into a cached singleton class named <>c; lambdas that capture variables go into a <>c__DisplayClass that holds the captured variables
  • This has nothing whatsoever to do with Amazon's AWS Lambda service

More information ​

Powered by Intracia