Foundations of Programming - Karl Seguin
Foundations of Programming - Karl Seguin
Foundations of Programming - Karl Seguin
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 />
public class Employee<br />
{<br />
private int _salary;<br />
public int Salary<br />
{<br />
get {return _salary;}<br />
set {_salary = value;}<br />
}<br />
public Employee(int startingSalary)<br />
{<br />
_salary = startingSalary;<br />
}<br />
}<br />
public class PayManagement<br />
{<br />
public static void Terminate(Employee employee)<br />
{<br />
employee = null;<br />
}<br />
public static void Terminate(ref Employee employee)<br />
{<br />
employee = null;<br />
}<br />
}<br />
public static void Main()<br />
{<br />
Employee employee1 = new Employee(10000);<br />
PayManagement.Terminate(employee1);<br />
Console.WriteLine(employee1.Salary);<br />
}<br />
Employee employee2 = new Employee(10000);<br />
PayManagement.Terminate(ref employee2);<br />
Console.WriteLine(employee2.Salary);<br />
Try to figure out what will happen and why. I'll give you a hint: an exception will be thrown. If you<br />
guessed that the call to employee1.Salary outputted 10000 while the 2nd one threw a<br />
NullReferenceException then you're right. In the first case we're simply setting a copy <strong>of</strong> the<br />
original pointer to null - it has no impact whatsoever on what employee1 is pointing to. In the second<br />
case, we aren't passing a copy but the same stack value used by employee2. Thus setting the employee<br />
to null is the same as writing employee2 = null;.<br />
It's quite uncommon to want to change the address pointed to by a variable from within a separate<br />
method - which is why the only time you're likely to see a reference type passed by reference is when<br />
you want to return multiple values from a function call (in which case you're better <strong>of</strong>f using an out<br />
parameter, or using a purer OO approach). The above example truly highlights the dangers <strong>of</strong> playing in<br />
an environment whose rules aren't fully understood.<br />
<strong>Foundations</strong> <strong>of</strong> <strong>Programming</strong> Copyright © <strong>Karl</strong> <strong>Seguin</strong> www.codebetter.com<br />
60