Re: Object equals
- From: "PvdG42" <pvan@xxxxxxxxxxxxx>
- Date: Sun, 27 Jan 2008 17:08:39 -0600
"tshad" <tfs@xxxxxxxxxxxxxx> wrote in message news:#LN16aTYIHA.6140@xxxxxxxxxxxxxxxxxxxxxxx
I am looking at the object equals methods and am confused.
I was under the impression that o.equals compares content (not whether they are the same object as o1==o2 does).
But in my example, this doesn't seem to be happening.
If I have a class Account and I create 2 objects with this class exactly the same way - the content should be equal (I would think).
Here is the code I am running and all the results make sense to me except the a3.Equals(a4) which should be true.
**************************************
Account a3 = new Account(1000.0, "Count Dracula", 500);
Account a4 = new Account(1000.0, "Count Dracula", 500);
if (a3 == a4)
Console.WriteLine("a3 == a4");
else
Console.WriteLine("a3 != a4");
if (a3.Equals(a4))
Console.WriteLine("a3.Equals(a4)");
else
Console.WriteLine("a3.NotEquals(a4)");
Console.WriteLine("\na3 content:");
a3.Report();
Console.WriteLine("\na4 content:");
a4.Report();
a3 = a4;
if (a3 == a4)
Console.WriteLine("\nAfter a3=a4 a3==a4");
else
Console.WriteLine("\nAfter a3=a4 a3!=a4");
***************************************
The results:
******************************
a3 != a4
a3.NotEquals(a4) <--- Should be equal as the next set shows content the same
a3 content:
Account Name: Count Dracula
Balance: 1000
Overdraft Limit: 500
Penalty: 25
a4 content:
Account Name: Count Dracula
Balance: 1000
Overdraft Limit: 500
Penalty: 25
After a3=a4 a3==a4
********************************
Why is a3.Equals(a4) showing as not equal?
Thanks,
Tom
From the Object class Equals method docs:
<quote>
The default implementation of Equals supports reference equality only, but derived classes can override this method to support value equality.
For reference types, equality is defined as object equality; that is, whether the references refer to the same object. For value types, equality is defined as bitwise equality. The ValueType class supports value types.
</quote>
To get the behavior you seek, you must override the Equals() method in your class to do a field by field comparison.
.
- References:
- Object equals
- From: tshad
- Object equals
- Prev by Date: Re: Object equals
- Next by Date: Re: Object equals
- Previous by thread: Re: Object equals
- Next by thread: Re: Object equals
- Index(es):
Relevant Pages
|