CHAPTER 4 CORE C# PROGRAMMING CONSTRUCTS, PART II
}
// Be sure to change your constructor name to PointRef!
public PointRef(int XPos, int YPos)
{
X = XPos;
Y = YPos;
}
Now, make use of your PointRef type within the following new method. Note that beyond using the
PointRef class, rather than the Point structure, the code is identical to the ValueTypeAssignment()
method.
static void ReferenceTypeAssignment()
{
Console.WriteLine("Assigning reference types\n");
PointRef p1 = new PointRef(10, 10);
PointRef p2 = p1;
// Print both point refs.
p1.Display();
p2.Display();
}
// Change p1.X and print again.
p1.X = 100;
Console.WriteLine("\n=> Changed p1.X\n");
p1.Display();
p2.Display();
In this case, you have two references pointing to the same object on the managed heap. Therefore,
when you change the value of X using the p1 reference, p2.X reports the same value. Assuming you have
called this new method within Main(), your output should look like the following:
Assigning reference types
X = 10, Y = 10
X = 10, Y = 10
=> Changed p1.X
X = 100, Y = 10
X = 100, Y = 10
Value Types Containing Reference Types
Now that you have a better feeling for the basic differences between value types and reference types,
let’s examine a more complex example. Assume you have the following reference (class) type that
maintains an informational string that can be set using a custom constructor:
class ShapeInfo
{
public string infoString;
151