Equivalence versus Identity

Equivalence depends on the value or state of an instance. Related objects that have the same value are equivalent. Identity is the location of an object. Objects can be equivalent but have different identities.

In the following code, integer variables locala and localc are equivalent—they contain the same value. However, the variables are not identical because they are stored at different locations on the stack. The variables locala and localb are neither equivalent nor identical. They have different values and are stored at different locations on the stack:

int locala = 5;
int localb = 10;
int localc = 5;

Assigning a value type copies the value. The target and source are equivalent after the following assignment, but they are not identical:

locala = localb;  // locala and localb are equivalent.

For reference types, there is synchronicity of equivalence and identity. Related references containing the same value are equivalent and identical because they refer to the same object. Assigning a reference to another reference creates an alias, which can create unplanned side effects. For this reason, be careful when assigning references. The following code has some unplanned side effects:

using System;

namespace Donis.CSharpBook {

    public class XInt {
        public int iField = 0;
    }

    public class Starter {
        public static void Main() {
            XInt obj1 = new XInt();
            obj1.iField = 5;
            XInt obj2 = new XInt();
            obj2.iField = 10;

            // Alias created and second instance lost
            obj2 = obj1;
            obj1.iField = 15; // side affect
            Console.WriteLine("{0}", obj2.iField); // Writes 15
        }
    }
}

The object obj2 is assigned obj1. They are now both identical and equivalent. Essentially, obj2 has become an alias for obj1, which means that changes to either object will affect the other.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.166.131