Equality in the C# Language
All things in Software programming are not equal even when they seem equal. Understanding of Equality is very important. Misunderstand can lead to program anomalies and undesirable artifacts.
There are Primarily Two Types in C#:
Value Types – Objects that reside on the “Stack”
Reference Types – Objects that reside on the “Managed Heap”
The criteria and methodology that the C# run-time evaluates equality is quite different between the two.
A clear understanding of the differences is essential to good programming practices
The Evaluation of Two Types for Equality in C# is Referred to as a Comparison
What is Equality?
The Mathematical Properties of Equality:
Equality is Reﬂexive, Symmetric, and Transitive.
The Reflexive Property: a == a
This is a “Reflexive State” or has “Reflexivity”.
The Reﬂexive property states that any object is equal to itself, no matter what type is involved.
a == a is always a True Statement.
The Symmetric Property: a == b then b == a
This is a “Symmetrical Relationship”.
The Symmetric Property states that Order Does Not Matter.
If a == b Is True then b == a is True likewise if a == b is False then b == a is also False
The Transitive Property: If a == b and b == c then a == c
This is a “Transitive Relationship”
a will always equal c if a is equal to b and b is equal to c
This concept may seem a little complicate or maybe even self-evident but it plays out differently when used in comparison operations in C#.
The Elements of Equality in the C# Language
There are Six ways to express Equality in C#:
– Two Static Methods
– An Overridable Equals Method
– An Overridable == Operator
– Two Interfaces
These links will provide you with the details of the six different possibilities:
The Static Methods should never be overridden as they always accomplish what they are intended to accomplish
You should look to create your own instance “Equals(object right)” method to define the semantics of your Type.
You should look to occasionally override “operator == (object left, object right)”. This override is typically for performance reasons in value types.
The above defined complexity is primarily due to the fact that C# enables you to create both Value Types and Reference Types that supports Equality comparisons
– Two variables of a reference type are equal if they refer to the same object, referred to as object identity.
– Two variables of a value type are equal if they are the same type and they contain the same contents.
That’s why C# Equality requires so many options
Our intent is not to provide an exhausted study of C# Equality
… Our intent is to expose the C# Equality Concept
…… to help improve The Modern Developer’s Art of C#