Thursday, July 1, 2010

Equality in C# – Part 1



In normal programming practice we always have a need to compare two variables. In C# we have two major choices for accomplishing this task

1) Using == operator

2) Using .Equals method.

When we use == operator it actually checks the references of objects and will return same result as object.ReferenceEquals, if there is no overloaded implementation for == exists for that type.

Lets talk about behavior of == and .Equals in different cases

A) Value type : (primitive type). All value type like int, double is inherited from “System.ValueType” class which overloads .Equals method. The overloaded implementation of .Equals method uses reflection to check equality which in turn very slows. == Operator in this case has default implementation which check the actual value store in the primitive type (as Value types are stored in stacks so their actual value will be compared).

B)String Type: implementation of String overloads both == and .Equal methods to ensure equality of content not identity.


String s1 = "test";
      String s2="test";

      //true ,true , true
      Console.WriteLine (String.Format("{0} {1} {2}",s1==s2,s1.Equals(s2), object.ReferenceEquals (s1,s2))); 

      // Now lets change their refrence.
      s1 = "1test".Substring(1);

      //output true ,true , false       
      Console.WriteLine(String.Format("{0} {1} {2}", s1 == s2, s1.Equals(s2), object.ReferenceEquals(s1, s2)));
 




C) Other Reference Type : For other reference types we need to give our own implantation of .Equals and == operator.

Rules to implement .Equal method

1) If you are planning to implement .Equal method then try to implement
through IEquatable interface to ensure type safety implementation.
2) Overload == and != operator methods to ensure same functionality
as .Equal overloaded method
3) Avoid calling base.Equals method.
4) Implement GetHasCode() method with .Equal method.

In next part I will explain why GetHashCode() method is necessary while implementing .Equals method.

No comments: