Skip to content

Lambda expressions C# 3.0readabilitynew scenarios

A concise syntax for writing functions and expressions.

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

Code

C#
delegate Image ImageProcessor(Image image);

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

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

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

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

void Save(IEnumerable<Image> images)
{
    Image 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 compiler will create a singleton class named <>c and put your anonymous method there
  • This has nothing whatsoever to do with Amazon's AWS Lambda service

More information