O'Reilly logo

Programming C# 4.0 by Jesse Liberty, Matthew Adams, Ian Griffiths

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Value Types and Reference Types

So far, we’ve been building a class. When creating an instance of the class, we stored it in a named variable, as Example 3-24 shows.

Example 3-24. Storing a reference in a variable

Plane someBoeing777 = new Plane("BA0049");
someBoeing777.Direction = DirectionOfApproach.Approaching;

We can define another variable with a different name, and store a reference to the same plane in that new variable, as shown in Example 3-25.

Example 3-25. Copying a reference from one variable to another

Plane theSameBoeing777ByAnotherName = someBoeing777;

If we change a property through one variable, that change will be visible through the other. Example 3-26 modifies our plane’s Direction property through the second variable, but then reads it through the first variable, verifying that they really are referring to the same object.

Example 3-26. Using one object through two variables

theSameBoeing777ByAnotherName.Direction = DirectionOfApproach.Leaving;
if (someBoeing777.Direction == DirectionOfApproach.Leaving)
{
    Console.WriteLine("Oh, they are the same!");
}

As Shakespeare might have said, if only he’d found his true vocation as a C# developer:

That which we call someBoeing777 By any other name would smell as sweet.

Assuming you like the smell of jet fuel.

When we define a type using class, we always get this behavior—our variables behave as references to an underlying object. We therefore call a type defined as a class a reference type.

Note

It’s possible for a reference type variable ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required