CHAPTER 4 CORE C# PROGRAMMING CONSTRUCTS, PART II
}
public ShapeInfo(string info)
{
infoString = info;
}
Now assume that you want to contain a variable of this class type within a value type named
Rectangle. To allow the caller to set the value of the inner ShapeInfo member variable, you also provide a
custom constructor. Here is the complete definition of the Rectangle type:
struct Rectangle
{
// The Rectangle structure contains a reference type member.
public ShapeInfo rectInfo;
public int rectTop, rectLeft, rectBottom, rectRight;
public Rectangle(string info, int top, int left, int bottom, int right)
{
rectInfo = new ShapeInfo(info);
rectTop = top; rectBottom = bottom;
rectLeft = left; rectRight = right;
}
}
public void Display()
{
Console.WriteLine("String = {0}, Top = {1}, Bottom = {2}, " +
"Left = {3}, Right = {4}",
rectInfo.infoString, rectTop, rectBottom, rectLeft, rectRight);
}
At this point, you have contained a reference type within a value type. The million dollar question
now becomes, what happens if you assign one Rectangle variable to another? Given what you already
know about value types, you would be correct in assuming that the integer data (which is indeed a
structure- System.Int32) should be an independent entity for each Rectangle variable. But what about
the internal reference type? Will the object’s state be fully copied, or will the reference to that object be
copied? To answer this question, define the following method and invoke it from Main():
static void ValueTypeContainingRefType()
{
// Create the first Rectangle.
Console.WriteLine("-> Creating r1");
Rectangle r1 = new Rectangle("First Rect", 10, 10, 50, 50);
// Now assign a new Rectangle to r1.
Console.WriteLine("-> Assigning r2 to r1");
Rectangle r2 = r1;
// Change some values of r2.
Console.WriteLine("-> Chang