This is something that has been bugging me for some time. When exactly
should I be using == instead of .Equals() ?
The == operator uses the static method op_Equality while Equals is an
instance method inherited from Object. Since the methods are members of each
class, or inherited from a base class, the implementation will vary from
class to class. However, in most scenarios you should get the same result if
whether you use the == operator or the Equals method.
To explain the differences I will use the String class as an example.
The String class inherits the instance method Equals from System.Object, has
an overloaded == operator and has its own static Equals method. The String
class can have a static method with the same name as the instance method
Equals inherited from Object since the methods have different signatures.
When using the == operator, the String class uses the static Equals method
internally. This method first uses the == operator to check if the strings
to compare are the same object. This is equal to using the
Object.ReferenceEquals mehtod.
If neither of the strings to compare are null, the static Equals method
calls the instance method Eqauls on the string to the left of the operator
and passes the string to the right of the operator as a parameter to perform
a string compare.
The C# compiler ensures that all strings with the same content all point to
the same object. Both s1, s2 and s3 in the following example point to the
same physical string object in memory, and hence have reference equality.
string s1="abc";
string s2="abc";
string s2=new string(new char[] {'a','b','c'});
When string comparsions the == operator is slower than the Equals method
when the strings are the same. If the strings are different the Equals
method will be faster. However, string comparison in .NET is super fast, so
in a real world application this won't make a difference.
Using the Equals operator determines whether two Object instances are the
same. The == operator determines whether two Objects have the same value.
Keep in mind that user-defined types can overload the == operator and the
Equals method alter their behavior.
Anders Norås
http://dotnetjunkies.com/weblog/anoras/