Compare structures with C#

  • Thread starter Thread starter Gianco
  • Start date Start date
G

Gianco

Hello people

I have the following problem, probably it has an easy solution but I
don't know how to solve it:

There's a structure with many fields, with this structure I create a
variable named, for instance 'A'. Then I create a second variable
named 'B'. I would save the complete content of A into B with one or
few commands (not copying field by field) and, later, check if A is
different from B, with C/C++ is very easy, first I make a memcpy of A
into B then, to see if something is different I can use the memcmp

How can do it with C#?

If I write 'B = A' B is just referenced to A so when I change
something into A, B has always the same content of A. And when I
compare A to B with 'if (A == B)' it gives me always true...

Sorry for the banal question, thanks in advance to anyone can help me

Gianco
 
Gianco said:
I have the following problem, probably it has an easy solution but I
don't know how to solve it:

There's a structure with many fields, with this structure I create a
variable named, for instance 'A'. Then I create a second variable
named 'B'. I would save the complete content of A into B with one or
few commands (not copying field by field) and, later, check if A is
different from B, with C/C++ is very easy, first I make a memcpy of A
into B then, to see if something is different I can use the memcmp

How can do it with C#?

If I write 'B = A' B is just referenced to A so when I change
something into A, B has always the same content of A. And when I
compare A to B with 'if (A == B)' it gives me always true...

Sorry for the banal question, thanks in advance to anyone can help me

It sounds like you're actually dealing with classes, not structs.

Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.
 
As you say doing something like 'B = A' means that A and B are pointing to
the same object. Thereafter A == B will always return true. It sounds like
you want to implement a "deep clone". Theres a debate a over whether you
should use the ICloneable interaface, I think the concensus is to avoid it
as it you cannot make a distinction between a shallow or deep copy.

Once you have a deep copy you can implement IComparable such that the
following will test for equality:

YourType A;
YourType B;

if(A.CompareTo(B) == 0)
{
//Same value;
}
 
Yes I supposed to work with a structure but it was declared as class,
now I changed something to use it as a structure and now make test if
the problem is solved. Thank you very much

Gianco
 
Back
Top