15.01.2013 Views

Foundations of Programming - Karl Seguin

Foundations of Programming - Karl Seguin

Foundations of Programming - Karl Seguin

SHOW MORE
SHOW LESS

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

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

Chapter 7 - Back to Basics: Memory<br />

ByRef<br />

Without a good understanding <strong>of</strong> pointers, it's virtually impossible to understand passing a value by<br />

reference and by value. Developers generally understand the implication <strong>of</strong> passing a value type, such as<br />

an integer, by reference, but few understand why you'd want to pass a reference by reference. ByRef<br />

and ByVal affect reference and value types the same - provided you understand that they always work<br />

against the underlying value (which in the case <strong>of</strong> a reference type means they work against the pointer<br />

and not the value). Using ByRef is the only common situation where .NET won't automatically resolve<br />

the pointer indirection (passing by reference or as an output parameter isn't allowed in Java).<br />

First we'll look at how ByVal/ByRef affects value types. Given the following code:<br />

public static void Main()<br />

{<br />

int counter1 = 0;<br />

SeedCounter(counter1);<br />

Console.WriteLine(counter1);<br />

}<br />

int counter2 = 0;<br />

SeedCounter(ref counter2);<br />

Console.WriteLine(counter2);<br />

private static void SeedCounter(int counter)<br />

{<br />

counter = 1;<br />

}<br />

private static void SeedCounter(ref int counter)<br />

{<br />

counter = 1;<br />

}<br />

We can expect an output <strong>of</strong> 0 proceeded by 1. The first call does not pass counter1 by reference,<br />

meaning a copy <strong>of</strong> counter1 is passed into SeedCounter and changes made within are local to the<br />

function. In other words, we're taking the value on the stack and duplicating it onto another stack<br />

location.<br />

In the second case we're actually passing the value by reference which means no copy is created and<br />

changes aren't localized to the SeedCounter function.<br />

The behavior with reference types is the exact same, although it might not appear so at first. We'll look<br />

at two examples. The first one uses a PayManagement class to change the properties <strong>of</strong> an Employee.<br />

In the code below we see that we have two employees and in both cases we're giving them a $2000<br />

raise. The only difference is that one passes the employee by reference while the other is passed by<br />

value. Can you guess the output?<br />

<strong>Foundations</strong> <strong>of</strong> <strong>Programming</strong> Copyright © <strong>Karl</strong> <strong>Seguin</strong> www.codebetter.com<br />

58

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

Saved successfully!

Ooh no, something went wrong!