Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

Share this Page URL

Chapter 22: Delegates > 22.3 Delegate invocation - Pg. 642

22.3 DELEGATE INVOCATION 609 Func f = new Func(val.ReadThenUpdate); // creates a boxed copy of val int a = f(6); // a = 42 int b = f(8); // b = 6 = 37; // does not effect copy of val used by f int c = f(b); // c = 8 Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c); } The delegate f refers to a boxed copy of val and not to val itself. Therefore, any changes to are not visible to f, and vice-versa. When the method ConcreteBox is invoked, the output is: a = 42, b = 6, c = 8 The C# pimpernel... Without resorting to unsafe code (§27), the boxed copy of a value type used by a delegate is a very elusive creature. It is impossible to first create the box and then the delegate. Continuing with the previous example, consider the statements: ValueType val_obj = val; // box val Func f2 = new Func(val_obj.ReadThenUpdate); // compile-time error The delegate creation is invalid as there is no ReadThenUpdate method on System. ValueType. Within an instance method of a value type, this (§18.3.6) is a reference parameter (§12.1.5), so, continuing with our example, a method may be added to Storage: