14.6. Passing method parameters by reference in delegates

It is possible for methods to take in parameters by reference instead of by value using either the ref or out keywords (see section 7.2).

In the case of a composite delegate instance, the methods in the invocation list are invoked in sequence. Since each method is invoked with the same set of parameters as that given to the delegate instance, for passed-by-reference parameters, each method invocation will be passed the same reference. This means that changes to that variable by one method in the invocation list will be passed in to the remaining methods. Study the example below:

 1:  using System;
 2:
 3:  delegate void MyDelegate (ref int i);
 4:
 5:  class TestClass{
 6:
 7:    static void MyMethod(ref int val){
 8:      Console.WriteLine("running M1 with parameter "+val);
 9:      val+=1;
10:    }
11:
12:    public static void Main(){
13:
14:      MyDelegate d1 = new MyDelegate(TestClass.MyMethod);
15:      MyDelegate compositeDelegate = d1 + d1 + d1 + d1;
16:
17:      int i = 1;
18:      compositeDelegate(ref i);
19:    }
20:  }

Output:

c:expt>test
running M1 with parameter 1
running M1 with parameter 2
running M1 with parameter 3
running M1 with parameter 4

On line 15, a composite delegate instance is created which encapsulates four references to TestClass.MyMethod. When the first MyMethod in the invocation list is invoked on line 18, it increments the value of the int passed to it by reference so that when the MyMethod is called a second time, it is passed a reference to the same int variable (which now contains the value of 2). This explains the output.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.37.156