Thursday, October 21, 2010

evolving delegate syntax in C#

In framework 1.0:
//1. declare the delegate signature - takes two int, and returns int
delegate int Add(int firstNumber, int secondNumber);

//2.create a function matches with the above delegate signature
private int AddNumbers(int firstNumber, int secondNumber)
{
return firstNumber + secondNumber;
}

//3. instantiate the delegate
Add add = new Add(this.AddNumbers);

//4. call the delegate to get the result
int result = add(Convert.ToInt32(this.txtFirst.Text), Convert.ToInt32(this.txtSecond.Text));

In framework 2.0:

Now you can have anonymous method.

//1. declare the delegate signature - takes two int, and returns int
delegate int Add(int firstNumber, int secondNumber);

//2. now you can instantiate the delegate with the anonymous method body inside of the brackets. 2. and 3. steps in framework 1.0 are now merged into one step as below
Add add = delegate(int firstNumber, int secondNumber)
{
return firstNumber + secondNumber;
};

//3.same here to call the delegate to get the result
int result = add(Convert.ToInt32(this.txtFirst.Text), Convert.ToInt32(this.txtSecond.Text));

In framework 3.5:

First, you can instantiate the delegate with lambda expressions

//1. declare the delegate signature - takes two int, and returns int
delegate int Add(int firstNumber, int secondNumber);

//2. now you can instantiate the delegate with lambda expressions. This below step does the exact same thing as the step 2 in framework 2.0.
Add add = (firstNumber, secondNumber) => firstNumber + secondNumber;

//3. same here to call the delegate to get the result
int result = add(Convert.ToInt32(this.txtFirst.Text), Convert.ToInt32(this.txtSecond.Text));

Second, you can also use the new Func delegate.

For example, we need the Func to have 2 input int and a return int as above. This below pre-defined one in .NET will suit us well:

public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2);

//1. below line combines delegate delcaration, delegate instantiation, as well as the function body in lambda expression altogether.
Func<int, int, int> add = (firstNumber, secondNumber) => firstNumber + secondNumber;

//2. then to use same way to get the result.
int result = add(Convert.ToInt32(this.txtFirst.Text), Convert.ToInt32(this.txtSecond.Text));

Get it? It's now reducing from 4 lines of coding to 2 lines to achieve the exact same thing from Framework 1.0 to 3.5. Nice!

No comments:

Post a Comment