Study Notes – C#: Equality()

public virtual bool Equals(
	object obj
)

Reference Types

  • Reference types – Evaluates reference equality
  • Can be overridden – need to do a bunch of other things
  • String, delegates and tuple reference types – override object.Equals. e.g. String will compare the value not the reference

Values Types

  • Value Types – Evaluates value equality
  • System.Object -> System.ValueType -> All value types
  • System.ValueType overrides object.Equals and compares every field determined by reflection and calling the equals method  -> SLOW

 

public static bool Equals(
	object objA,
	object objB
)
  • If both objects are provided then either could be null so calling object.Equals() will fail. The static method handles nulls.
  • It checks for nulls – if both are not null then will call object.Equals
  • Therefore if you override object.Equals the static method will call the overridden method and the behavior will be the same.

 

public static bool ReferenceEquals(
	object objA,
	object objB
)
  • Because object.Equals() can’t be overridden it’s not guaranteed to compare the reference
  • Demonstrate by using strings that override object.Equals() and compares the value
  • Cannot be overridden because it’s static

 

IEquatable<T>.Equals(T other)
  • Object.Equals(object obj) – takes an object
  • It does this so it’s method signiture can be overridden for any type
  • Therefore NOT TYPE SAFE
  • Reference types will be boxed -> performance hit
  • IEquatable.<T>.Equals(T other) – can be exposed to provide strongly typed equals
  • .NET implements this for value types – but not on all non-primitive value types
  • Not so useful for reference types since there is no performance saving and doesn’t work well with inheritance because of the conflict between inheritance and equality
  • Is implemented for string reference type because string is sealed and cannot be overridden and also compares values
  • Where both IEquatable<T>.Eqauls(T other) and object.Equals(obj object) they do exactly the same thing.