CHAPTER 4 CORE C# PROGRAMMING CONSTRUCTS, PART II
Value Types, References Types, and the Assignment Operator
When you assign one value type to another, a member-by-member copy of the field data is achieved. In
the case of a simple data type such as System.Int32, the only member to copy is the numerical value.
However, in the case of your Point, the X and Y values are copied into the new structure variable. To
illustrate, create a new Console Application project named ValueAndReferenceTypes, then copy your
previous Point definition into your new namespace. Next, add the following method to your Program
type:
// Assigning two intrinsic value types results in
// two independent variables on the stack.
static void ValueTypeAssignment()
{
Console.WriteLine("Assigning value types\n");
Point p1 = new Point(10, 10);
Point p2 = p1;
// Print both points.
p1.Display();
p2.Display();
}
// Change p1.X and print again. p2.X is not changed.
p1.X = 100;
Console.WriteLine("\n=> Changed p1.X\n");
p1.Display();
p2.Display();
Here, you have created a variable of type Point (named p1) that is then assigned to another Point
(p2). Because Point is a value type, you have two copies of the MyPoint type on the stack, each of which
can be independently manipulated. Therefore, when you change the value of p1.X, the value of p2.X is
unaffected:
Assigning value types
X = 10, Y = 10
X = 10, Y = 10
=> Changed p1.X
X = 100, Y = 10
X = 10, Y = 10
In stark contrast to value types, when you apply the assignment operator to reference types
(meaning all class instances), you are redirecting what the reference variable points to in memory. To
illustrate, create a new class type named PointRef that has the exact same members as the Point
structures, beyond renaming the constructor to match the class name:
// Classes are always reference types.
class PointRef
{
// Same members as the Point structure...
150