A delegate is a type-safe reference to a method. Prior to C# 2.0 a delegate instance could only reference an existing named method. Now, a delegate may also point to a block of code defined in-line where the delegate is created.
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
: delegate (Image image) { return image; };
int idx = 1;
foreach(Image 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;
}
Image NoProcessing(Image image)
{
return image;
}
void Save(IEnumerable images)
{
ImageProcessor processImage = highContrastMode
? new ImageProcessor(HighContrast)
: new ImageProcessor(NoProcessing);
int idx = 1;
foreach(Image image in images)
processImage(image).Save("Image" + idx++, ImageFormat.Jpeg);
}Notes
- Anonymous methods can capture local variables and parameters from the enclosing method (closures), something a separate named method could only do via fields or a hand-written helper class
- The parameter list can be omitted entirely (
delegate { ... }) when the body does not use the parameters - The current compiler puts non-capturing anonymous methods into a cached singleton class named
<>c; capturing ones go into a<>c__DisplayClassthat holds the captured variables - C# 2.0 also added implicit method group conversions, so
ImageProcessor p = NoProcessing;no longer needsnew ImageProcessor(...)
WARNING
This syntax was superseded by Lambda expressions C# 3.0.