Skip to content

Invoking Delegates with Return Values

If a delegate has a return value and more than one method in its invocation list, the following occurs:

  • The value returned by the last method in the invocation list is the value returned
    from the delegate invocation.
  • The return values from all the other methods in the invocation list are ignored.

 

For example, the following code declares a delegate that returns an int value. Main creates an object of the delegate and adds two additional methods. It then calls the delegate in the WriteLine statement and prints its return value. Below figure shows a graphical representation of the code.

				
					delegate int MyDel( ); // Declare delegate with return value.
class MyClass 
{
    int IntValue = 5;
    public int Add2() { IntValue += 2; return IntValue;}
    public int Add3() { IntValue += 3; return IntValue;}
}

class Program 
{
    static void Main( ) 
    {
        MyClass mc = new MyClass();
        MyDel mDel = mc.Add2; // Create and initialize the delegate.
        mDel += mc.Add3; // Add a method.
        mDel += mc.Add2; // Add a method.
        Console.WriteLine($"Value: { mDel() }");
    }
}

//Invoke the delegate and use the return value.

This code produces the following output:
Value: 12
				
			

Leave a Reply

Your email address will not be published.