#401 – Every Object Inherits an Equals Method
August 31, 2011 Leave a comment
Every type inherits directly or indirectly from System.Object, so each has an Equals method. This includes both value types (which inherit from System.ValueType) and reference types (which inherit from System.Object).
public virtual bool Equals(Object object);
The Equals method returns true if the object passed in to the method is equal to the object on which the method was called.
System.Object includes a default implementation of the Equals method that :
- For value types, returns true if the underlying values are the same (even though there are two copies of the value)
- For reference types, returns true if the references refer to the exact same object in memory
float f1 = 10.2f; float f2 = 10.2f; bool sameFloat = f1.Equals(f2); // true - same value Dog kirby = new Dog("Kirby", 13); Dog kirby2 = new Dog("Kirby", 13); bool sameDog = kirby.Equals(kirby2); // false - two different objects Dog kirby3 = kirby; sameDog = kirby3.Equals(kirby); // true - two references to same object