Possible Duplicate:
C# difference between==and .Equals()
For comparing two variables we can use == or Equals method. for example,
string a = new string(new char[] {'a', 'b', 'c', 'd'});
string b = new string(new char[] {'a', 'b', 'c', 'd'});
Console.WriteLine (a==b);
Console.WriteLine (a.Equals(b));
My question is When should I use == and when should I use Equals? Is there any difference between the two?
== is an operator, which, when not overloaded means “reference equality” for classes (and field-wise equality for structs), but which can be overloaded. A consequence of it being an overload rather than an override is that it is not polymorphic.
Equals is a virtual method; this makes it polymorphic, but means you need to be careful not to call it on null instances.
As a rule of thumb:
EqualityComparer<T>.Default.Equals(a,b)which avoids the null issue, supports Nullable-of-T, and supports IEquatable-of-T