Delegates: Named methods, Anonymous methods, Lamda expressions (C#)
June 8, 2009 – 6:18 pmDelegates
The declaration of a delegate type is similar to a method signature.
A delegate is a reference type that can be used to encapsulate a named or an anonymous method. Delegates are similar to function pointers in C++.
public delegate void TestDelegate(string message); public delegate int TestDelegate(MyType m, long num);
Delegates are the basis for Events.
A delegate can be instantiated by associating it either with a named or anonymous method.
Pre-declared delegates
The .NET framework has a number of pre-declared delegates (ie. method signatures) so you may avoid explicitly declaring custom delegates.
public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2)
Declaring delegate instances…
In versions of C# before 2.0, the only way to declare a delegate instance was to use named methods. C# 2.0 introduced anonymous methods and in C# 3.0 and later, lambda expressions supersede anonymous methods as the preferred way to write inline code.
Named method
// Declare a delegate: delegate void Del(int x); // Define a named method: void DoWork(int k) { /* … */ } // Instantiate the delegate using the method as a parameter: Del d = obj.DoWork;
Anonymous method
// Create a delegate instance delegate void Del(int x); // Instantiate the delegate using an anonymous method Del d = delegate(int k) { /* … */ };
By using anonymous methods, you reduce the coding overhead in instantiating delegates because you do not have to create a separate method.
Lambda expressions
A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.
All lambda expressions use the lambda operator =>, which is read as “goes to”. The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * x is read “x goes to x times x.” This expression can be assigned to a delegate type as follows:
delegate int del(int i); del myDelegate = x => x * x; int j = myDelegate(5); //j = 25
d