I am trying to understand concept of delegates and have got a query. Suppose that we have a delegate defined with return type as int and accepting in 2 parameters of type int.
Delegate declaration:
public delegate int BinaryOp(int x, int y);
Now, lets say we have 2 methods (add and multiply) both accepting 2 int parameters and returning an int result.
Code:
static int Add(int x, int y)
{
return x + y;
}
static int Multiply(int x, int y)
{
return x * y;
}
Now, when add and multiply methods are added into this delegate, and then when the delegate is called like:
BinaryOp b = new BinaryOp(Add);
b+=new BinaryOp(Multiply);
int value=delegate_name(2,3);
Then, as per my understanding, both the methods are called. Now, result from which of the 2 methods is stored in the value variable? Or does it return an array in such case?
delegate: It is the keyword which is used to define the delegate. return_type: It is the type of value returned by the methods which the delegate will be going to call. It can be void. A method must have the same return type as the delegate.
If you have a method that accepts two numbers and you want to add them and return the sum of the two numbers, you can use a delegate to store the return value of the method as shown in the code snippet given below. int result = d(12, 15);
Multicast Delegates must have a return type of void Otherwise it will throw an exception.
A delegate is a type safe and object oriented object that can point to another method or multiple methods which can then be invoked later. It is a reference type variable that refers to methods.
You will get the return value of the last method added to the multicast delegate. In this case, you will get the return value of Multiply
.
See the documentation for more on this: https://msdn.microsoft.com/en-us/library/ms173172.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With