Monday, June 28, 2010

C# tip - 6/28/2010 (making up for the weekend)

Differences between four equality methods/operations:

  • public static bool ReferenceEquals(object, object)
    • returns true if objects refer to the same object.  It does not care about the object contents
Obj obj = new Obj();
Object.ReferenceEquals(obj,obj) returns true
Obj obj2 = obj;
Object.ReferenceEquals(obj,obj2) returns true
Obj obj3 = new Obj();
Object.ReferenceEquals(obj,obj3) returns false
Int32 i = 1;
Object.ReferenceEquals(i,i) returns false
Int32 i2 = i;
Object.ReferenceEquals(i,i2) returns false

  • public static bool Equals(object, object)
    • returns true if the objects are equal at runtime.  It uses the instance Equals methods to compare the objects if they are identical.


Obj obj = new Obj();
Object.Equals(obj,obj) returns true
Obj obj2 = obj;
Object.Equals(obj,obj2) returns true
Obj obj3 = new Obj();
Object.Equals(obj,obj3) returns false
Int32 i = 1;
Object.Equals(i,i) returns true
Int32 i2 = i;
Object.Equals(i,i2) returns true

  • public virtual bool Equals(object)
    • compares the object calling the method with the object passed in the method.  This is an overridable method.  The reason for that is because the default Equals method has to check for EVERY type possible since it doesn't know which type the object is until runtime.  One example is the ValueType, which is the base for all value types.  It will have to use reflection at runtime to get the runtime type of the object.  To improve the performance of this method, override it for your concrete class and only check for those conditions that you deem necessary.
    • To override the method properly, use the following pattern:
      1. check that the object parameter is not null (return false)
      2. check identity with ReferenceEquals method (return true if it is)
      3. check that the types are the same (return false)
      4. compare the objects' contents
    • do NOT throw exceptions out of this method
    • do NOT use as operation since that will incorrectly convert the object of subtype into a base type.
      • example: 
        • parameterObject is type BaseType, which SubyType extends
        • SubType test = parameterObject as SubType will always return NULL
        • parameterObject2 is type SubType
        • BaseType test = parameterObject2 as BaseType will return the object
      • use object.getType() instead
    • write the override for GetHashCode as well if this is done
  • public static bool operator ==(Class left, Class right)
    • override when dealing with value types


No comments:

Labels