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.