12.07.2015 Views

Accelerated

Accelerated

Accelerated

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

112CHAPTER 4 ■ CLASSES, STRUCTS, AND OBJECTSref ArgumentsPassing parameters by reference is indicated by placing the ref modifier ahead of the parametertype in the parameter list for the method. When a variable is passed by reference, a new copy of thevariable is not made, and the caller’s variable is directly affected by any actions within the method.As is usually the case in the CLR, this means two slightly different things, depending on whether thevariable is an instance of a value type (struct) or an object (class).When a value instance is passed by reference, a copy of the caller’s value is not made. It’s as ifthe parameter were passed as a C++ pointer, even though you access the methods and fields of thevariable in the same way as value arguments. When an object (reference) instance is passed by reference,again, no copy of the variable is made, which means that a new reference to the object onthe heap is not created. In fact, the variable behaves as if it were a C++ pointer to the reference variable,which could be viewed as a C++ pointer to a pointer. Additionally, the verifier ensures that thevariable referenced by the ref parameter has been definitely assigned before the method call. Let’stake a look at some examples to put the entire notion of ref parameters into perspective:using System;public struct MyStruct{public int val;}public class EntryPoint{static void Main() {MyStruct myValue = new MyStruct();myValue.val = 10;PassByValue( myValue );Console.WriteLine( "Result of PassByValue: myValue.val = {0}",myValue.val );}PassByRef( ref myValue );Console.WriteLine( "Result of PassByRef: myValue.val = {0}",myValue.val );}static void PassByValue( MyStruct myValue ) {myValue.val = 50;}static void PassByRef( ref MyStruct myValue ) {myValue.val = 42;}This example contains two methods: PassByValue and PassByRef. Both methods modify a fieldof the value type instance passed in. However, as the following output shows, the PassByValuemethod modifies a local copy, whereas the PassByRef method modifies the caller’s instance as youwould expect:Result of PassByValue: myValue.val = 10Result of PassByRef: myValue.val = 42

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!