more effective csharp notes

<>笔记

Item 9: Equality

  1. public static bool ReferenceEquals(object left, object right);
    • Never redefine
    • Return true: same reference identity
    • Specially, return false when compare two value type variable(due to boxing)
  2. public static bool Equals(object left, object right);
    • Never redefine
    • Call ReferenceEquals and instance Equals() to comapre two object instances
  3. public virtual bool Equals(object right);

    • Equality
      • reflexive: a == a
      • symmetric: a == b <--> b == a
      • transitive: a == b, b == c –> a == c
    • Default
      • Reference type: same with Object.ReferenceEquals()
      • Value type: have been override by System.ValueType, but we should create an override of ValueType.Equals() when we create a value type.
    • How to override
      • Impliment IEquatable<T>
      • Impliment GetHashCode()
        • Equal objects must produce equal hash codes
        • Hash code must be object invariants
        • Must produce an even distribution to be efficient
      • Standard pattern
        public class Foo : IEquatable<Foo>
        {
        public override bool (object right)
        {

        // This reference is never null in C# methods
        if (object.ReferenceEquals(right, null))
        return false;
        if (object.ReferenceEquals(this, right))
        return true;

        // To handle inheritance hierarchy problem
        if (this.GetType() != right.GetType())
        return false;

        // Compare this type's contents here:
        return this.Equals(right as Foo);
        }

        // IEquatable<Foo> Members
        public bool (Foo other)
        {
        // Elided: this.x == other.x && this.y == other.y, etc.
        return true;
        }

        }
  4. public static bool operator ==(MyClass left, MyClass right);

    • Redefine for value type, not reference type