CSharp - Type Creation Equality Comparison

Value Versus Referential Equality

There are two kinds of equality:

Type Meaning
Value equalityTwo values are equivalent in some sense.
Referential equality Two references refer to exactly the same object.

By default:

  • Value types use value equality.
  • Reference types use referential equality.

A simple value equality is to compare two numbers:

int x = 5, y = 5;
Console.WriteLine (x == y);   // True (by virtue of value equality)

The following prints True because the two DateTimeOffsets refer to the same point in time and so are considered equivalent:

var dt1 = new DateTimeOffset (2010, 1, 1, 1, 1, 1, TimeSpan.FromHours(8));
var dt2 = new DateTimeOffset (2010, 1, 1, 2, 1, 1, TimeSpan.FromHours(9));
Console.WriteLine (dt1 == dt2);   // True

Reference types use referential equality by default.

The following f1 and f2 are not equal-despite their objects having identical content:

class Test {
  public int X;
}

Test f1 = new Test { X = 5 };
Test f2 = new Test { X = 5 };

Console.WriteLine (f1 == f2);   // False

f3 and f1 are equal because they reference the same object:

Test f3 = f1;
Console.WriteLine (f1 == f3);   // True