Testing equality of pens

G

Guest

Hi

I'm trying to test if two Pen objects are equal as shown below

Pen p1 = new Pen(Color.Black)
Pen p2 = new Pen(Color.Black)

if (p1.Equals(p2)

Console.WriteLine("These pens equal")


The problem is that the if statement doesn't return true, I would have thought that p1 and p2 are the same. Is the only way round this to write my own function which compares every single property of Pen? That would be very laborious and time consuming

Help much appreciated

Tristan.
 
C

ChrisM

Sorry I can't help. I always thought that

if (p1.Equals(p2))

would compare to see if the objects were equivilent (ie refered to 2
distinct objects that had identical properties)

and

if (Pen.Equals(p1,p2))

would check to see if both referenced the same object.
So I would have thought that your comparison would work.

However, on investigation, I found the following: at
http://msdn.microsoft.com/library/d...f/html/frlrfsystemobjectclassequalstopic1.asp

Remarks
The default implementation of Equals supports reference equality only, but
derived classes can override this method to support value equality.

So like you say, I guess you will have to write a method that compares all
the properties that are important to you in this situation. What a PITA!

ChrisM

Tristan said:
Hi,

I'm trying to test if two Pen objects are equal as shown below:

Pen p1 = new Pen(Color.Black);
Pen p2 = new Pen(Color.Black);

if (p1.Equals(p2))
{
Console.WriteLine("These pens equal");
}

The problem is that the if statement doesn't return true, I would have
thought that p1 and p2 are the same. Is the only way round this to write my
own function which compares every single property of Pen? That would be very
laborious and time consuming!
 
N

noah

Hi,
both p1 and p2 are two object references. If they were int /
string / long / double / DateTime or other value types, such an equals
test would work.

From the MSDN library, Pen->Public Methods, you have:
Equals (inherited from Object).

The Object.Equals method only test if two object *references* are
equal. If you did the following:
Pen p1 = new Pen(Color.Black);
Pen p2 = p1; //sets the object reference p2 to p1
then
p1.Equals(p2) ===> TRUE

hope this helps,
Noah
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top