I found a possible scenario w.r.t. MultiCast Delegates which I am not able to get around. I am not able to assign multiple methods to a Delegate object in the Main class. Only the last method is getting registered with the delegate. In this case, it's the Subtract()
method. Is there a restriction around that which I am not aware of?
static void Main(string[] args)
{
Calculator calc = new Calculator();
//Create a Delegate object
CalcDelegate delObj, delObj2, delObj3, delObj4;
CalcDelegate delObj5 = null;
//Register methods with delegate objects
delObj = new CalcDelegate(calc.Add);
delObj2 = new CalcDelegate(calc.Subtract);
delObj3 = (CalcDelegate)Delegate.Combine(delObj, delObj2);
Console.WriteLine(delObj3.Method);
delObj4 = delObj + delObj2;
Console.WriteLine(delObj3(40, 20));
Console.WriteLine(delObj4(40, 20));
delObj5 += calc.Add;
delObj5 += calc.Subtract;
Console.WriteLine(delObj5(40, 20));
Console.ReadKey();
}
Here's my implementation of the Calculator class along with the delegate:
public delegate int CalcDelegate(int a, int b);
public class Calculator
{
public int Add(int x, int y)
{
return x + y;
}
public int Subtract(int x, int y)
{
return x - y;
}
}