#402 – Value Equality vs. Reference Equality

When we normally think of “equality”, we’re thinking of value equality–the idea that the values stored in two different objects are the same.  This is also known as equivalence.  For example, if we have two different variables that both store an integer value of 12, we say that the variables are equal.

            int i1 = 12;
            int i2 = 12;

            // Value equality - evaluates to true
            bool b2 = (i1 == i2);

The variables are considered “equal”, even though we have two different copies of the integer value of 12.

We can also talk about reference equality, or identity–the idea that two variables refer to exactly the same object in memory.

            Dog d1 = new Dog("Kirby", 15);
            Dog d2 = new Dog("Kirby", 15);
            Dog d3 = d1;

            bool b1 = (d1 == d2);   // Evaluates to false
            bool b2 = (d1 == d3);   // Evaluates to true

In C#, the == operator defaults to using value equality for value types and reference equality for reference types.