#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.

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #402 – Value Equality vs. Reference Equality

  1. michel says:

    hmm, knew it, but reading it like this, it looks awkward that i1 == i2

  2. Pingback: #420 – Laundry List for Implementing Value Equality and IComparable « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: