Skip to content

delegate keyword pre lambda

Context: Before C# 3.0, anonymous methods were written using the delegate keyword. They can still be used but are largely superseded by lambdas.

delegate(parameters) { statements }
Action<string> print = delegate(string msg)
{
Console.WriteLine(msg);
};
Func<int, int> doubleIt = delegate(int x)
{
return x * 2;
};

Same as lambdas: they create closures.

int factor = 3;
Func<int, int> multiply = delegate(int x) { return x * factor; };

Compatibility with C# 2.0: If you need to write code that compiles on .NET Framework 2.0, you must use anonymous methods instead of lambdas.

Example: In some legacy ASP.NET WebForms, you might still see delegate used in event handlers.