Tim Hibbard

CEO for EnGraph software
posts - 628 , comments - 1631 , trackbacks - 459

My Links

News



Add to Google

Twitter












Tag Cloud

Article Categories

Archives

Post Categories

Image Galleries

EnGraph Blogs

Links

Other

Roll

More thoughts on Equals()

I agree with Dru's comment on my post yesterday about overriding Equals().  I now want to implement a static function into my objects that will compare two objects.  Again, I'm stuck between two ways of doing it.  I could accept specific  object types (static bool Equals(MyObject a, MyObject b)) or just accept an object type and cast it (static bool Equals(object a, object b)).  I'm leaning towards the latter way as it allows me to define that method into the interface that all my objects already implement.  But as I look through the .NET framework, Microsoft used the first way.

Assuming I have an object called Audit, here are the ways I'm trying to implement it.

The first way:

public static bool Equals(Audit a, Audit b) { bool rv = true; try { //compare } catch (Exception) { rv = false; } return rv; }

The second way:

public new static bool Equals(object a, object b) { bool rv = true; try { Audit first = (Audit)a; Audit second = (Audit)b; //compare } catch (Exception) { rv = false; } return rv; }

I guess I could implement both ways and let the consumer decide which one to use, but I don't have a way to enforce that with an interface.  Any thoughts?

 

Technorati tags: , ,

Print | posted on Wednesday, March 14, 2007 10:25 AM | Filed Under [ .NET ]

Feedback

Gravatar

# re: More thoughts on Equals()

Hi Tim, why a static method? If you are worried about nullness checkout the ?? operator, its wicked cool.

Also, why not just implement .Equals() and then use the System.Object.Equals if you need a static method. Check it out in reflector, if nothing else for inspiration for your own static. -d
3/14/2007 11:44 AM | dru
Gravatar

# re: More thoughts on Equals()

I wanted a static method so I could call:
Audit.Equals(someAudit, anotherAudit);

Since I'm already overriding Equals(), I can use the built in Object.Equal(obj1,obj2). I didn't even think about that.

Also, I can't implement a static method in an interface in C# anyways, so my whole thought process behind this post is flawed :)
3/14/2007 11:53 AM | Tim Hibbard
Gravatar

# re: More thoughts on Equals()

It's all good in the hood. :)
3/14/2007 8:48 PM | dru
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: