473,386 Members | 1,647 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,386 software developers and data experts.

equality

I am a C++ guy recently migrated to C#. One of the thing I don't understand
is assignment (=) and equality (==) operators. If I try to do the following:

C a = new C;
C b = a;

Then I will get both a and b referring to the same object, which is not
exactly the copy constructor semantics in C++. But I can do the following to
remedy:

C c = new C(a);

But, what if I try to assign an object with another object? An assignment
operator only tries get the lvalue referring to the rvalue, so far I guess.

c = a; //now a, b and c are refering to the same object

Another situation I can get myself out is the use of equality operator (==).
So what does the semantic imply? Are they to answer "are the two references
referring to the same object?" or "are they equal by calling the overloaded
operator ==, if any?"

C d = new C;
C e = new C(d);
bool i = (d == e); //what do you say?

ben
Nov 16 '05 #1
6 1812

"benben" <be******@yahoo.com.au> wrote in message
news:%2***************@tk2msftngp13.phx.gbl...
I am a C++ guy recently migrated to C#. One of the thing I don't understand
is assignment (=) and equality (==) operators. If I try to do the
following:

C a = new C;
C b = a;

Then I will get both a and b referring to the same object, which is not
exactly the copy constructor semantics in C++. But I can do the following
to
remedy:

C c = new C(a);
Right..it is not supposed to match copy constructor semantics however.
I would advise against trying to use copy constructors in .NET. They don't
work at all with interfaces and aren't particularly inuitive when it comes
to classes. What if C is actually a DerivedC implementation? A copy
constructor ends up breaking down the object chain. Note, .NET in general
and C# specifically don't define copy constructors and you shouldn't expect
*any* class to have one. If it does thats fine, but its far from guarenteed.
Many of the C(C val) type constructors you will see are actually using
containment or delegation and not copying.

There is a vauge pattern supported with the ICloneable interface, but it is
weak enough that there has been some discussion of obsoleting it.[1]

But, what if I try to assign an object with another object? An assignment
operator only tries get the lvalue referring to the rvalue, so far I
guess.

c = a; //now a, b and c are refering to the same object
Yes, this too is expected. Its actually pretty fundamental to the design of
the system. Note that this doesn't occur with value types (structs in C#),
only reference types.

Another situation I can get myself out is the use of equality operator
(==).
So what does the semantic imply? Are they to answer "are the two
references
referring to the same object?" or "are they equal by calling the
overloaded
operator ==, if any?"

C d = new C;
C e = new C(d);
bool i = (d == e); //what do you say?
It depends. if C overrides an equal operator, you may or may not get true.
If it doesn't, you will get false. Remember, since C# doesn't directly
understand copy constructors, there is no reason to assume that new C(d) is
a copy...it may be an aggregate or many other things.

Note, however, that overriden operators are based on variable type, so that

object d = new C();
object e = new C(d);
bool i = (d == e);
uses objects ==, which will result in i == false;

you can use Object.ReferenceEquals to verifiably compare references, but
otherwise you have no way of knowing how the comparison between two objects
is going to work outside of documentation telling you.

You might also want to read
http://blogs.msdn.com/csharpfaq/arch...29/102224.aspx
1. http://blogs.msdn.com/brada/archive/...03/125427.aspx
ben

Nov 16 '05 #2
Hashtable a = new Hashtable();
Hashtable b = new Hashtable();
a.Add("1","2");
b.Add("1","2");
System.Diagnostics.Debug.WriteLine(a==b);
....will return False.

ArrayList a = new ArrayList();
ArrayList b = new ArrayList();
a.Add("2");
b.Add("2");
System.Diagnostics.Debug.WriteLine(a==b);
....will return False.

string[] a = new string[]{"2","3"};
string[] b = new string[]{"2","3"};
string[] c = a;
System.Diagnostics.Debug.WriteLine(a==b);
System.Diagnostics.Debug.WriteLine(a==c);
....will return False, then True.

string a = "TEST";
string b = "TEST";
System.Diagnostics.Debug.WriteLine(a==b);
....will return True.

So my guess is that it will default to compare memory address of objects,
but use class operators if they exist.

Example:
public class Complex
{
private double real;
private double imag;

public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.Real+c2.Real, c1.Imag+c2.Imag);
}

public static Complex operator -(Complex c1, Complex c2)
{
return new Complex(c1.Real-c2.Real, c1.Imag-c2.Imag);
}
// ...
}

--
-Wolf5
(When replying directly to me, remove the parenthesises in the reply
address)
Nov 16 '05 #3
BenBen... I think the simplest explanation is that C++ classes use value
semantics by default and C# classes use reference semantics. (C#
structures
use value semantics.) This obviates the absolute need for a copy
constructor
in C# since you can have two references to the same object on the heap.
In
C# the object will only be collected when the object is unreachable so
you
don't need to worry about the "destructor" being called more than once
for a
given object on the heap. In other words, if you create two references
to a
single object, the destructor will only be called once, not twice. As a
result
there is no need to do a deep copy during assignment and no absolute
need
for a copy constructor in C#.

http://www.geocities.com/jeff_louie/OOP/oop5.htm

Regards,
Jeff
I am a C++ guy recently migrated to C#. One of the thing I don't

understand is assignment (=) and equality (==) operators. <

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #4
benben <be******@yahoo.com.au> wrote:
I am a C++ guy recently migrated to C#. One of the thing I don't understand
is assignment (=) and equality (==) operators.


See

http://www.pobox.com/~skeet/csharp/faq/#equals
http://www.pobox.com/~skeet/csharp/parameters.html

The latter primarily covers parameter passing, but should help you
understand assignment when it comes to reference types.
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #5
Why would you say if C is a derived class then a copy constructor will break
down the object chain? What is the "object chain" in the sense?

And with a class C which contains a defined C operator = (object o), what is
the semantic I will assume when interpreting the following assignments?

C a, b;
a = new C;
b = a;
C d = new C;
d = a;

I honestly do think with all these reference types C# could become an even
more ambiguous language than already ambiguous C++.

What if I have two references to object(s) which are of class in which
operator = () is defined and I try to test their identity? In C++ I can
always test againt their addresses, &a == &b. What is the equivalent
statement in C#?

Ben

"benben" <be******@yahoo.com.au> wrote in message
news:%2***************@tk2msftngp13.phx.gbl...
I am a C++ guy recently migrated to C#. One of the thing I don't understand is assignment (=) and equality (==) operators. If I try to do the
following:

C a = new C;
C b = a;

Then I will get both a and b referring to the same object, which is not
exactly the copy constructor semantics in C++. But I can do the following to
remedy:

C c = new C(a);
Right..it is not supposed to match copy constructor semantics however.
I would advise against trying to use copy constructors in .NET. They don't
work at all with interfaces and aren't particularly inuitive when it comes
to classes. What if C is actually a DerivedC implementation? A copy
constructor ends up breaking down the object chain. Note, .NET in general
and C# specifically don't define copy constructors and you shouldn't

expect *any* class to have one. If it does thats fine, but its far from guarenteed. Many of the C(C val) type constructors you will see are actually using
containment or delegation and not copying.

There is a vauge pattern supported with the ICloneable interface, but it is weak enough that there has been some discussion of obsoleting it.[1]

But, what if I try to assign an object with another object? An assignment operator only tries get the lvalue referring to the rvalue, so far I
guess.

c = a; //now a, b and c are refering to the same object
Yes, this too is expected. Its actually pretty fundamental to the design

of the system. Note that this doesn't occur with value types (structs in C#),
only reference types.

Another situation I can get myself out is the use of equality operator
(==).
So what does the semantic imply? Are they to answer "are the two
references
referring to the same object?" or "are they equal by calling the
overloaded
operator ==, if any?"

C d = new C;
C e = new C(d);
bool i = (d == e); //what do you say?
It depends. if C overrides an equal operator, you may or may not get true.
If it doesn't, you will get false. Remember, since C# doesn't directly
understand copy constructors, there is no reason to assume that new C(d)

is a copy...it may be an aggregate or many other things.

Note, however, that overriden operators are based on variable type, so that
object d = new C();
object e = new C(d);
bool i = (d == e);
uses objects ==, which will result in i == false;

you can use Object.ReferenceEquals to verifiably compare references, but
otherwise you have no way of knowing how the comparison between two objects is going to work outside of documentation telling you.

You might also want to read
http://blogs.msdn.com/csharpfaq/arch...29/102224.aspx
1. http://blogs.msdn.com/brada/archive/...03/125427.aspx

ben


Nov 16 '05 #6
benben <be******@yahoo.com.au> wrote:
Why would you say if C is a derived class then a copy constructor will break
down the object chain? What is the "object chain" in the sense?

And with a class C which contains a defined C operator = (object o), what is
the semantic I will assume when interpreting the following assignments?
Not sure what you meant by the above, but you can't override the
assignment operator in C#.
C a, b;
a = new C;
b = a;
C d = new C;
d = a;
(Assuming changes of syntax from "new C;" to "new C();")

That creates two objects. One ends up being garbage almost immediately.
The final result is three variables all with the same value - namely a
reference to the object which was created first.
I honestly do think with all these reference types C# could become an even
more ambiguous language than already ambiguous C++.
Not at all - I don't see what's ambiguous about the above.
What if I have two references to object(s) which are of class in which
operator = () is defined and I try to test their identity?
I don't see how overriding the assignment operator is relevant. Do you
mean overriding the identity operator (==, not =)?
In C++ I can
always test againt their addresses, &a == &b. What is the equivalent
statement in C#?


Object.ReferenceEquals(a, b) will always test whether a and b are
references to the same object. Alternatively, a cast of either side to
object will force the "original" (as in for Object) meaning of == to be
used:

if ((object)a == b)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #7

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

Similar topics

26
by: Alexander Block | last post by:
Hello newsgroup, let's say I have a function like template<class Type> inline bool areEqual(const Type &a, const Type &b) { return ( a == b ); }
40
by: Ike Naar | last post by:
In K&R "The C++ programming language (2nd ANSI C edition), the reference manual states (paragraphs 7.9 and 7.10) that pointer comparison is undefined for pointers that do not point to the same...
4
by: Matt Burland | last post by:
I'm a little confused about the way the default equality operator works with classes. Here's the situation, I have two comboboxes that are each filled with different object (i.e. ComboBox1 contains...
2
by: Marcel Sottnik | last post by:
Hallo NG Does anyone have an idea how could one implement, a general routine for value equality ? I mean something using Reflections to get all the members of a class and compare them...
6
by: onetitfemme | last post by:
Hi *, I have been looking for a definition or at least some workable concept of "XML equality". Searching on "XML equality" in comp.text.xml, microsoft.public.xsl and microsoft.public.xml...
37
by: spam.noam | last post by:
Hello, Guido has decided, in python-dev, that in Py3K the id-based order comparisons will be dropped. This means that, for example, "{} < " will raise a TypeError instead of the current...
7
by: Gary Brown | last post by:
Hi, In C#, how do you determine two objects are the "same" rather than "equal?" In C/C++ you can check the addresses and LISP provides a rich set of equality operators but C# appears ambiguous....
6
by: Edward Diener | last post by:
Now that operator overloading allows to ref classes to be compared for equality using == syntax, how does one compare the actual ref pointers ( ^ ) for equality instead ? As an example: ...
3
by: toton | last post by:
Hi, I have a struct Point { int x, int y; } The points are stored in a std::vector<Pointpoints; (global vector) I want to add equality (operator == ) for the point, which will check equality...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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,...
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...

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.