473,396 Members | 1,849 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

op_Equality (== Operator) for Value-Types

Hi,

I have a, probably very basic, query on value-types.

Why cannot I use the == operator directly for value-types (not primitive
types like int, float, double etc)? Why do I need to either have an implicit
operator (to type-cast to primitive type) or override/overlaod the ==
operator myself?


--
Happy Hacking,
Gaurav Vaish | www.mastergaurav.com
www.edujini-labs.com
http://eduzine.edujini-labs.com
-----------------------------------------

Mar 20 '07 #1
10 4442
On Tue, 20 Mar 2007 16:39:17 +0530, "MasterGaurav
\(www.edujini-labs.com\)" <ga*****************@nospam.gmail.com>
wrote:
Why cannot I use the == operator directly for value-types (not primitive
types like int, float, double etc)? Why do I need to either have an implicit
operator (to type-cast to primitive type) or override/overlaod the ==
operator myself?
I'm assuming what you want is a default definition of operator== for
value types that does a bitwise comparison of all member variables.

I agree that would have been convenient since it's normally exactly
what you want. No idea why the .NET team didn't do that. They might
have judged it not worth the effort since user-defined value types are
(or should be) rare.
--
http://www.kynosarges.de
Mar 20 '07 #2
MasterGaurav (www.edujini-labs.com) wrote:
Hi,

I have a, probably very basic, query on value-types.

Why cannot I use the == operator directly for value-types (not primitive
types like int, float, double etc)? Why do I need to either have an implicit
operator (to type-cast to primitive type) or override/overlaod the ==
operator myself?
Because a binary comparison of structures doesn't always make sense.

Example:

public struct Name {

private string _first, _last;

public Name(string first, last) {
_first = first; _last = last;
}

public string First { get { return _first; } }
public string Last { get { return _last; } }
}

Name person1 = new Name("Peter", "Parker");
string er = "er";
Name person2 = new Name("Pet" + er, "Park" + er);

Now you have two structures with different binary values, but the same
logical values.

--
Göran Andersson
_____
http://www.guffa.com
Mar 20 '07 #3
Different binary values? How's that? IMO, they (person1 and person2) are the
same, bit per bit.
The assignment will be made as strings with the same value, despite the
expression for person2.
"Göran Andersson" <gu***@guffa.comha scritto nel messaggio
news:Ox**************@TK2MSFTNGP04.phx.gbl...
MasterGaurav (www.edujini-labs.com) wrote:
>Hi,

I have a, probably very basic, query on value-types.

Why cannot I use the == operator directly for value-types (not
primitive types like int, float, double etc)? Why do I need to either
have an implicit operator (to type-cast to primitive type) or
override/overlaod the == operator myself?

Because a binary comparison of structures doesn't always make sense.

Example:

public struct Name {

private string _first, _last;

public Name(string first, last) {
_first = first; _last = last;
}

public string First { get { return _first; } }
public string Last { get { return _last; } }
}

Name person1 = new Name("Peter", "Parker");
string er = "er";
Name person2 = new Name("Pet" + er, "Park" + er);

Now you have two structures with different binary values, but the same
logical values.

--
Göran Andersson
_____
http://www.guffa.com

Mar 20 '07 #4
The standard does not allow for automatic operator overloading, by default,
as they are not CLS compliant.
If your language supports operator overloading, good for you, but you must
implement it by yourself.

Sometimes you must make your own implementation. For example:

public struct NamedBuffer
{
public readonly string bufferName;
byte[] myByte;

public NamedBuffer(string BufName)
{
bufferName = BufName;
myByte = new byte[65535];
}
}

static void Main(string[] args)
{
NamedBuffer buf1 = new NamedBuffer("hello");
NamedBuffer buf2 = new NamedBuffer("hello");
bool theSame = buf1.Equals(buf2);
}
The buffers are not same, if you let the system to use it's bitwise
comparision.

And, sometimes it's good to roll on your own for performance reasons.
"MasterGaurav (www.edujini-labs.com)" <ga*****************@nospam.gmail.com>
ha scritto nel messaggio news:OI**************@TK2MSFTNGP06.phx.gbl...
Hi,

I have a, probably very basic, query on value-types.

Why cannot I use the == operator directly for value-types (not
primitive types like int, float, double etc)? Why do I need to either have
an implicit operator (to type-cast to primitive type) or override/overlaod
the == operator myself?


--
Happy Hacking,
Gaurav Vaish | www.mastergaurav.com
www.edujini-labs.com
http://eduzine.edujini-labs.com
-----------------------------------------

Mar 20 '07 #5

"Laura T." <LT@NOWHERE.COMwrote in message
news:%2****************@TK2MSFTNGP05.phx.gbl...
Different binary values?
That's right.
How's that? IMO, they (person1 and person2) are the same, bit per bit.
That's your opinion, not real life.
The assignment will be made as strings with the same value, despite the
expression for person2.
The content of the two string objects will be the same. But strings are a
reference type. Each of the two string objects will be stored at a
different address, and it's that address which is contained within the value
type.

However, the compiler could easily provide an automatic member-by-member
equality operator, rather than as a raw blob. That's up to the language
designer though (the CLR doesn't prevent it).
Mar 20 '07 #6
On Mar 20, 12:44 pm, "Laura T." <L...@NOWHERE.COMwrote:
Different binary values? How's that? IMO, they (person1 and person2) are the
same, bit per bit.
Nope.
The assignment will be made as strings with the same value, despite the
expression for person2.
Strings are reference types. person1 and person2 will have references
to different strings, therefore the bit-for-bit contents of person1
and person2 will differ. The two string objects will be *equal*, but
they will still be separate objects.

Jon

Mar 20 '07 #7
Well, if you put it in that way, that references have different memory
location, yes, that would be right.
But that does not make person1 and person2 to be different for CLR (try
person1.Equals(person2);).
The automatic value type comparator uses field by field comparision when it
can (via System.RuntimeType.GetFieldCandidates) rather than strict memcmp,
so after the day, person1==person2 =true.
"Ben Voigt" <rb*@nospam.nospamha scritto nel messaggio
news:%2****************@TK2MSFTNGP05.phx.gbl...
>
"Laura T." <LT@NOWHERE.COMwrote in message
news:%2****************@TK2MSFTNGP05.phx.gbl...
>Different binary values?
That's right.
>How's that? IMO, they (person1 and person2) are the same, bit per bit.
That's your opinion, not real life.
>The assignment will be made as strings with the same value, despite the
expression for person2.
The content of the two string objects will be the same. But strings are a
reference type. Each of the two string objects will be stored at a
different address, and it's that address which is contained within the
value type.

However, the compiler could easily provide an automatic member-by-member
equality operator, rather than as a raw blob. That's up to the language
designer though (the CLR doesn't prevent it).

Mar 20 '07 #8
Laura T. wrote:
Well, if you put it in that way, that references have different memory
location, yes, that would be right.
But that does not make person1 and person2 to be different for CLR (try
person1.Equals(person2);).
That is because the Equals method is overridden in the String class to
compare the values of the strings instead of the references.
The automatic value type comparator uses field by field comparision when it
can (via System.RuntimeType.GetFieldCandidates) rather than strict memcmp,
so after the day, person1==person2 =true.
Yes, but that means that a default comparer would either have to use
reflection to compare the values (which isn't that effective), or it
would have to be created by the compiler.

If you would always have a default comparer, it means that you would be
forced to implement a comparer whenever the default comparer doesn't
make sense.

Also it implies that comparing values always makes sense. If it doesn't,
you would have to override the comparer and throw an exception if
someone tries to use it.
>
"Ben Voigt" <rb*@nospam.nospamha scritto nel messaggio
news:%2****************@TK2MSFTNGP05.phx.gbl...
>"Laura T." <LT@NOWHERE.COMwrote in message
news:%2****************@TK2MSFTNGP05.phx.gbl...
>>Different binary values?
That's right.
>>How's that? IMO, they (person1 and person2) are the same, bit per bit.
That's your opinion, not real life.
>>The assignment will be made as strings with the same value, despite the
expression for person2.
The content of the two string objects will be the same. But strings are a
reference type. Each of the two string objects will be stored at a
different address, and it's that address which is contained within the
value type.

However, the compiler could easily provide an automatic member-by-member
equality operator, rather than as a raw blob. That's up to the language
designer though (the CLR doesn't prevent it).


--
Göran Andersson
_____
http://www.guffa.com
Mar 20 '07 #9
The standard does not allow for automatic operator overloading, by
default, as they are not CLS compliant.
If your language supports operator overloading, good for you, but you must
implement it by yourself.
Wondering why is has not been overloaded in System.ValueType.

IMHO, if the method Equals has been overridden, it makes sense to overload
the op_Equality operator as well.
Well, may not be in general, but at least for value-types since we are
anyway checking for value.
--
Happy Hacking,
Gaurav Vaish | www.mastergaurav.com
www.edujini-labs.com
http://eduzine.edujini-labs.com
-----------------------------------------
Mar 23 '07 #10
MasterGaurav (www.edujini-labs.com) wrote:
>The standard does not allow for automatic operator overloading, by
default, as they are not CLS compliant.
If your language supports operator overloading, good for you, but you must
implement it by yourself.

Wondering why is has not been overloaded in System.ValueType.
Because that would make it impossible to create a CLR compliant assembly.
IMHO, if the method Equals has been overridden, it makes sense to overload
the op_Equality operator as well.
Well, may not be in general, but at least for value-types since we are
anyway checking for value.
Yes, often so, but you don't always want to compare all the values in a
structure.

Take for example a structure that handles the setting of a light dimmer:

public struct LightDimmer {

private bool _on;
private int _intendity;

public LightDimmer(bool on, int intensity) {
_on = on;
_intensity = intensity;
}

public bool On { get { return _on; } }
public bool Off { get { return !_on; } }
public int Intensity { get { return _intensity; } }

public static bool operator == (LightDimmer d1, LightDimmer d2) {
if (d1.Off && d2.Off) return true;
if (d1.Off || d2.Off) return false;
return d1.Intensity == d2.Intensity;
}

}

The on/off state is separate from the intensity setting, as a dimmer
keeps the intensity setting even when turned off.

If you compare two settings, and both are turned off, you want them to
be equal eventhough the intensity would be different if both were turned
on. If you would compare all the values of the structures without this
logic, they would be different eventhough both rooms are currently
equally dark.

--
Göran Andersson
_____
http://www.guffa.com
Mar 24 '07 #11

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

Similar topics

7
by: Paul Davis | last post by:
I'd like to overload 'comma' to define a concatenation operator for integer-like classes. I've got some first ideas, but I'd appreciate a sanity check. The concatenation operator needs to so...
30
by: | last post by:
I have not posted to comp.lang.c++ (or comp.lang.c++.moderated) before. In general when I have a C++ question I look for answers in "The C++ Programming Language, Third Edition" by Stroustrup....
1
by: joesoap | last post by:
Hi can anybody please tell me what is wrong with my ostream operator??? this is the output i get using the 3 attached files. this is the output after i run assignment2 -joesoap #include...
5
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...
0
by: Martin Magnusson | last post by:
I have defined a number of custom stream buffers with corresponding in and out streams for IO operations in my program, such as IO::output, IO::warning and IO::debug. Now, the debug stream should...
3
by: Sensei | last post by:
Hi. I have a problem with a C++ code I can't resolve, or better, I can't see what the problem should be! Here's an excerpt of the incriminated code: === bspalgo.cpp // THAT'S THE BAD...
14
by: lutorm | last post by:
Hi everyone, I'm trying to use istream_iterators to read a file consisting of pairs of numbers. To do this, I wrote the following: #include <fstream> #include <vector> #include <iterator> ...
6
by: YUY0x7 | last post by:
Hi, I am having a bit of trouble with a specialization of operator<<. Here goes: class MyStream { }; template <typename T> MyStream& operator<<(MyStream& lhs, T const &)
9
by: SpoonfulofTactic | last post by:
I am working on a new library for my own use that would allow me to use SI Units and to convert them back and forth with ease. However, While I have been working on operator overloading, I have...
9
by: Steve Sargent | last post by:
Hi: I'm trying to debug the following code, and it keeps looping on the if statement: public static bool operator == (OnlineMemberNode first, OnlineMemberNode second) { if(first == null) {
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.