Data Structures and Algorithms with Object-Oriented Design Patterns in C#
next up previous contents index

References Types

 

In C#, every variable that is not one of the value types is a reference type  . Such a variable can be thought of as a reference to (or a pointer to ) an object of the appropriate type.

Every object to which a reference variable refers is an instance of some C# class. In C#, class instances must be explicitly created. An instance of a class is created using the new operator like this:

Foo f = new Foo();
If we follow this with an assignment statement such as
Foo g = f;
then both f and g refer to the same object! Note that this is very different from what happens when you assign one value type to another.

A comparison of the the form

if (f == g)
    { /* ... */ }
usually tests whether the f and g refer to the same object instances (provided the equality operator has not be overriden). If f and g refer to distinct object instances that happen to be equal, the test still fails. To test whether two distinct object instances are equal, it is necessary to invoke the Equals method like this:
if (f.Equals(g))
    { /* ... */ }




next up previous contents index

Bruno Copyright © 2001 by Bruno R. Preiss, P.Eng. All rights reserved.