473,837 Members | 1,993 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

why can I overload the != operator??

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
Nov 16 '05 #1
17 2517
I guess one of the reasons might be that a more efficient implementation of
the != operator is possible than just negating the outcome of the equality
operator.

--
Sincerely,
Dmitriy Lapshin [C# / .NET MVP]
Bring the power of unit testing to the VS .NET IDE today!
http://www.x-unity.net/teststudio.aspx

"Chris" <ct******@hotma il.com> wrote in message
news:%2******** ********@TK2MSF TNGP11.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


Nov 16 '05 #2
> I guess one of the reasons might be that a more efficient implementation
of
the != operator is possible than just negating the outcome of the equality
operator.


I suppose you're right. In many situations it is easier to determine if
it's not equal than if it is. I do think that it should at least be
optional though. And if it isn't overloaded then the compiler just emits
what I mentioned earlier.

Chris
Nov 16 '05 #3
Chris --

I've wondered the same thing many times. As Dmitriy suggests, one
possibility is that there's a more efficient implementation for != (although
it would be interesting to come up with an example). That said, you'd think
the compiler would simply provide an implementation is you don't specify
one. The same goies for (<, >=) and (>, <=).

The other thing that bothers me is that, if you define:

static public bool operator ==(MyType x, MyOtherType o)
{
// Your implementation here
}

you also have to define

static public bool operator ==(MyOtherType o, MyType x)
{
return (x == o);
}

Since equality should always be symmetric, the order of the argument should
never matter. So, why must I define both operators?

Ken
"Chris" <ct******@hotma il.com> wrote in message
news:%2******** ********@TK2MSF TNGP11.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

Nov 16 '05 #4
I cannot believe they did it for performance. So why can't I overload +=
or -=, instead I have to overload operator+(T a,T b) which must always
return a copy of the object!

In my opinion the C# compiler should provide the != operator automatically
if == is overloaded.
The same should be true in the reverse case, but for the sake of performance
you could still explicity provide both operators.

The same should be true for < and >= or > and <= or operator==(Y a,X b) and
operator==(X b,Y a) or operator true and operator false.

I hope that microsoft will use this idea because it will highly increase
productivity and stability in some cases.

--
cody

[Freeware, Games and Humor]
www.deutronium.de.vu || www.deutronium.tk
"Chris" <ct******@hotma il.com> schrieb im Newsbeitrag
news:%2******** ********@TK2MSF TNGP11.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.

Nov 16 '05 #5
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" <ct******@hotma il.com> wrote in message
news:%2******** ********@TK2MSF TNGP11.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

Nov 16 '05 #6
Hi cody,

I thing += has nothing to do with performance.

First: you should always return an object form + and - operation in order to
be able to do

a = b + c + d +...+ z;
Second: since apparently you cannot overload = operation it make no sence to
overload += and -= because there is no more logic you could provide in this
overload.

--
Stoitcho Goutsev (100) [C# MVP]
"cody" <pl************ *************@g mx.de> wrote in message
news:Oh******** *****@TK2MSFTNG P10.phx.gbl...
I cannot believe they did it for performance. So why can't I overload +=
or -=, instead I have to overload operator+(T a,T b) which must always
return a copy of the object!

In my opinion the C# compiler should provide the != operator automatically
if == is overloaded.
The same should be true in the reverse case, but for the sake of performance you could still explicity provide both operators.

The same should be true for < and >= or > and <= or operator==(Y a,X b) and operator==(X b,Y a) or operator true and operator false.

I hope that microsoft will use this idea because it will highly increase
productivity and stability in some cases.

--
cody

[Freeware, Games and Humor]
www.deutronium.de.vu || www.deutronium.tk
"Chris" <ct******@hotma il.com> schrieb im Newsbeitrag
news:%2******** ********@TK2MSF TNGP11.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.


Nov 16 '05 #7
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.NotEqual s()). That could
certainly lead to confusion and to very bad logic errors if not used
carefully.

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

http://msdn.microsoft.com/library/de...lsoperator.asp

Ken
"Eric Gunnerson [MS]" <er****@online. microsoft.com> wrote in message
news:ek******** *****@TK2MSFTNG P11.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" <ct******@hotma il.com> wrote in message
news:%2******** ********@TK2MSF TNGP11.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


Nov 16 '05 #8
> I thing += has nothing to do with performance.

First: you should always return an object form + and - operation in order to be able to do

a = b + c + d +...+ z;
Second: since apparently you cannot overload = operation it make no sence to overload += and -= because there is no more logic you could provide in this overload.

So if you think what you're saying here is true think why
System.StringBu ilder has no operator+, but System.String has.

in order to implement +=,

string StringBuilder StringBuilder.o p_Addition(Stri ngBuilder
sb1,StringBuild er sb2)

would have to be implemented. And this method must return always a new
object in order to work properly. This fact would make the purpose of
StringBuilder very questionable.

--
cody

[Freeware, Games and Humor]
www.deutronium.de.vu || www.deutronium.tk
Nov 16 '05 #9
> 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.


No. Is SQL every operation where NULL is involved has to return false. That
means that NULL==NULL will also return false. Thats why you have to use
IsNull() for that purpose.

--
cody

[Freeware, Games and Humor]
www.deutronium.de.vu || www.deutronium.tk
Nov 16 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2083
by: bsaucer | last post by:
I am creating a class with operator overloads. It makes references to another class I've created, but do not wish to modify. I try to overload an operator having arguments having the other class type, but none of the new class type. However it does return a type of the new class. The compiler tells me that at least one parameter must be of the containing type. Is there a way to do this? The other class hos no reference to this new class. Is...
7
4346
by: Piotre Ugrumov | last post by:
I have tried to implement the overload of these 2 operators. ostream & operator<<(ostream &out, Person &p){ out<<p.getName()<<" "<<p.getSurname()<<", "<<p.getDateOfBirth()<<endl; return out; } This overload work but I have a curiosty If I try to approch to the name or to the surname or to the dateofbirth in this way i receive error: ostream & operator<<(ostream &out, Person &p){ out<<p.name<<" "<<p.surname<<", "<<p.dateofbirth<<endl;
1
2071
by: Piotre Ugrumov | last post by:
I'm following your help. I have written the overload of the operator <<. This overload work! :-) But I have some problem with the overload of the operator >>. I have written the overload of this least operator for the class Person, but I don't know how write the overload for a class that derived from the class Person. The overload of << in Person is this: ostream & operator<<(ostream &out, const Persona &p){ out<<p.getNome()<<"...
3
2252
by: Piotre Ugrumov | last post by:
I have done the overload on the operator >> and << in the class Attore. These 2 overload work correctly. I have done the overload of the same overload in the class Film. The class film ha inside an array of pointer to Attore. I have written these overload in these ways. the overload of << work correctly the overload of >> I don't know. I compile the class correctly, when I insert a film through the operator >> I don't receive error, but...
5
3810
by: Jason | last post by:
Hello. I am trying to learn how operator overloading works so I wrote a simple class to help me practice. I understand the basic opertoar overload like + - / *, but when I try to overload more complex operator, I get stuck. Here's a brief description what I want to do. I want to simulate a matrix (2D array) from a 1D array. so what I have so far is something like this: class Matrix
4
1900
by: Chiller | last post by:
Ok, thanks to some good assistance/advice from people in this group I've been able to further develop my Distance class. Since previous posts I've refined my code to accept the unit measurement as a char rather than incorrectly representing it as an int. I've done this because I want to develop the class so that it will be able to convert between values, ie if I add 500 m to 1 km I'd like a correct result given in metres (1500 m in this...
7
4679
by: Sean | last post by:
Can someone help me see why the following "operator=" overloading doesn't work under g++? and the error message is copied here. I see no reason the compiler complain this. Thanks, $ g++ copyconstructor1.cpp #copyconstructor1.cpp: In function `int main()': #copyconstructor1.cpp:86: no match for `sample& = sample' operator #copyconstructor1.cpp:53: candidates are: sample sample::operator=(sample&) ...
9
2392
by: Tony | last post by:
I have an operator== overload that compares two items and returns a new class as the result of the comparison (instead of the normal bool) I then get an ambiguous operater compile error when I attempt to check to see if the object is null: "The call is ambiguous between the following methods or properties: 'TestObject.operator ==(TestObject, string)' and 'TestObject.operator ==(TestObject, TestObject)" Does anyone have any idea how to...
3
5825
by: i3x171um | last post by:
To start off, I'm using GCC4. Specifically, the MingW (setjmp/longjmp) build of GCC 4.2.1 on Windows XP x64. I'm writing a class that abstracts a message, which can be either an integer (stored as long long int), a decimal (double), or a string (std::string). I basically want to overload most of a Message's operators so that the Message class feels more like a native type. For example... Message msg = "tester"; std::string str = msg;...
0
9846
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10890
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10634
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9416
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7819
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7007
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5855
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4479
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3127
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.