Delegates in C# – pre-lambda and post-lambda expressions
Delegates are amongst the most powerful constructs in the C# language (Full Solution Download at the end of this article).
Some uses of delegates in c# include :
- Delaying invocation(calling) of a method
- Dynamically assigning target(s) to a method
- Advanced eventing patterns using c# delegates – including publish subscribe
Pre-C# 3.0 days
In pre c# 3.0 days, the most common way of declaring and using a delegate in c# was:
- public class PreLambdaDelegate
- {
- // declare the delegate
- delegate int CalculateSum(int inta, int intb);
- // Instantiate delegate and call (Invoke) the method that the delegate points to
- public int InstantiateAndCallDelegate()
- {
- CalculateSum calculateDelegateInstance = new CalculateSum(DoActualCalculation);
- return calculateDelegateInstance.Invoke(3, 5);
- }
- private int DoActualCalculation(int int1, int int2)
- {
- return int1 + int2;
- }
- }
The code is self-explanatory – we declare the delegate, then instantiate it, then invoke it (invoke the method that it is pointing to).
Post C# 3.0 days – Enter Lambda Expressions
Lambda expressions provide a more compact way of accomplishing the same result as above:
- public class PostLambdaExpressionsDelegate
- {
- // declare delegate (this part is the same as PreLambdaWay)
- delegate int CalculateSum(int inta, int intb);
- // create instance and call delegate using an anonymous method
- public int InstantiateAndCall()
- {
- CalculateSum doCalc = (x, y) =>
- {
- return x + y;
- };
- return doCalc(5,6);
- }
- }
Notice that we did not need to actually instantiate the delegate. All we had to do was call the method by using a lambda expression (x,y) and an assignment operator (=>) . With the help of these two constructs (lambda expression and an assignment operator), our code is simplified. To run the samples above, use a simple main program as shown below:
- class Program
- {
- static void Main(string[] args)
- {
- PreLambdaDelegate preLambda = new PreLambdaDelegate();
- int result1 = preLambda.InstantiateAndCallDelegate();
- Console.WriteLine(“Pre Lambda Delegate Result = “ + result1);
- PostLambdaExpressionsDelegate postLambda = new PostLambdaExpressionsDelegate();
- int result2 = postLambda.InstantiateAndCall();
- Console.WriteLine(“Post LambdaExpressions Delegate Result = “ + result2);
- }
- }
Leave a Reply