[...]
Is there any difference between using == or Equals?
Yes.
Should I use Equals?
It depends on what behavior you want.
If there is an == operator overload, and if you are using variables typed
as the actual type for which the overload you want to use is defined, then
the two should be the same. But otherwise, calling the Equals() methodis
generally preferred because it provides reliable behavior regardless of
the declared type of the variables being used.
The == overload used is determined at compile-time, without run-time type
information about the objects being compared, while the Equals() method
called, being a virtual method in the Object class, is determined at
run-time based on the type of the objects being compared.
Very rarely, you _don't_ want the polymorphic behavior of Equals(). For
example, using the == operator is a shortcut for calling the
Object.ReferenceEquals() method, as long as the two variables being used
are both declared as System.Object types (not usually the case, but it
does come up).
IMHO, polymorphic types with Equals() method overrides and the == operator
being overloaded don't mix very well, because of this disparity. When
both have been done, it can lead to some subtle bugs. And in fact, youdo
have to be pretty careful when dealing with System.String objects to make
sure you're using a comparison that produces the expected results in a
given context. But, as long as you remember to only ever use the ==
operator in a context where you know the exact type of the objects being
compared and that type is the type of the variables being compared, you
should be fine.
Eric Lippert's most recent blog post actually touches on this, somewhat
tangentially, as part of a discussion on the string interning behavior in
.NET:
http://blogs.msdn.com/ericlippert/archive/2009/09/28/string-interning...
Pete