Re: why can I overload the != operator??

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance

From: Ken Kolda (ken.kolda_at_elliemae-nospamplease.com)
Date: 07/08/04


Date: Thu, 8 Jul 2004 14:06:34 -0700

While I can see your point, my issue is that, based on Microsoft's own
recommendations:

1) If you overload "==" you should always overload the Object.Equals()
method.
2) If you overload "==", Object.Equals() and operator == should always
return the same value.

Now, if you override operator != and return something other than the
negation of operator ==, there's no way to do this in an equivalent manner
with Object.Equals (because there's no Object.NotEquals()). That could
certainly lead to confusion and to very bad logic errors if not used
carefully.

Here's Microsoft's remcommendations with regards to operator == and
Object.Equals():

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconimplementingequalsoperator.asp

Ken

"Eric Gunnerson [MS]" <ericgu@online.microsoft.com> wrote in message
news:ekRgKFSZEHA.716@TK2MSFTNGP11.phx.gbl...
> There are some types for which this doesn't hold true. The Sql types, for
> example, use three state logic, and by SQL rules, null is neither equal
nor
> not equal to a specific value.
>
> --
> Eric Gunnerson
>
> Visit the C# product team at http://www.csharp.net
> Eric's blog is at http://weblogs.asp.net/ericgu/
>
> This posting is provided "AS IS" with no warranties, and confers no
rights.
> "Chris" <ctlajoie@hotmail.com> wrote in message
> news:%23aRsHFQZEHA.4032@TK2MSFTNGP11.phx.gbl...
> > To me, this seems rather redundant. The compiler requires that if you
> > overload the == operator, you must also overload the != operator. All I
> do
> > for the != operator is something like this:
> >
> > public static bool operator !=(MyType x, MyType y)
> > {
> > return !(x == y);
> > }
> >
> > That way the == operator handles everything, and extra comparing logic
> isn't
> > needed. I think the C# compiler should NOT allow overloading of the !=
> > operator, and instead just emit the code I just showed.
> >
> > I could be completely off my rocker, but this has puzzled me for some
time
> > now, and I just had to ask if someone knows the purpose of allowing the
!=
> > operator to be overloaded.
> >
> > Chris
> >
> >
>
>