Skip to content

Anonymous methods C# 2.0code reduction

Create a delegate using an inline function body.

A delegate is a variable that references a function. Prior to C# 2.0 a delegate was only permitted to reference an existing method. Now, a delegate may also point to a block of code defined in-line with the variable declaration.

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)
{
    ImageProcessor processImage = highContrastMode
        ? (ImageProcessor)HighContrast
        : delegate (Image image) { return image; };

    int idx = 1;
    foreach(Image 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;
}

Image NoProcessing(Image image)
{
    return image;
}

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

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

Notes

  • The compiler creates a singleton class named <>c and put your anonymous method there

WARNING

This syntax was superseded by Lambda expressions C# 3.0.

More information