CHAPTER 4 CORE C# PROGRAMMING CONSTRUCTS, PART II
}
// Print values of both rectangles.
r1.Display();
r2.Display();
The output can be seen in the following:
-> Creating r1
-> Assigning r2 to r1
-> Changing values of r2
String = This is new info!, Top = 10, Bottom = 50, Left = 10, Right = 50
String = This is new info!, Top = 10, Bottom = 4444, Left = 10, Right = 50
As you can see, when you change the value of the informational string using the r2 reference, the r1
reference displays the same value. By default, when a value type contains other reference types,
assignment results in a copy of the references. In this way, you have two independent structures, each of
which contains a reference pointing to the same object in memory (i.e., a shallow copy). When you want
to perform a deep copy, where the state of internal references is fully copied into a new object, one
approach is to implement the ICloneable interface (as you will do in Chapter 8).
Source Code The ValueAndReferenceTypes project is located under the Chapter 4 subdirectory.
Passing Reference Types by Value
Reference types or value types can, obviously, be passed as parameters to methods. However, passing a
reference type (e.g., a class) by reference is quite different from passing it by value. To understand the
distinction, assume you have a simple Person class defined in a new Console Application project named
RefTypeValTypeParams, defined as follows:
class Person
{
public string personName;
public int personAge;
// Constructors.
public Person(string name, int age)
{
personName = name;
personAge = age;
}
public Person(){}
public void Display()
{
Console.WriteLine("Name: {0}, Age: {1}", personName, personAge);
}
153