Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling delegate with multiple functions having return values

Tags:

c#

delegates

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?

like image 793
helloworld Avatar asked May 02 '15 06:05

helloworld


People also ask

Can delegates return type?

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.

Can delegate return a value?

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);

What should be the return type of multicast delegate methods?

Multicast Delegates must have a return type of void Otherwise it will throw an exception.

Can a delegate point to more than 1 method?

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.


1 Answers

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

like image 97
Asad Saeeduddin Avatar answered Oct 22 '22 13:10

Asad Saeeduddin