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

1 int i1 = 12;

2 int i2 = 12;

3 

4 // Value equality - evaluates to true

5 bool b2 = (i1 == i2);

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

#402 - Value Equality vs. Reference Equality

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

1 Dog d1 = new Dog("kirby", 15);

2 Dog d2 = new Dog("kirby", 15);

3 Dog d3 = d1;

4 

5 bool b1 = (d1 == d2);   // Evaluates to false

6 bool b2 = (d1 == d3);   // Evaluates to true

#402 - Value Equality vs. Reference Equality

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

原文地址:#402 - Value Equality vs. Reference Equality

你可能感兴趣的:(reference)