Geeks With Blogs


Add to Google

Tim Hibbard CEO for EnGraph software

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: , ,
Posted on Wednesday, March 14, 2007 10:25 AM .NET | Back to top

Comments on this post: More thoughts on Equals()

# re: More thoughts on Equals()
Requesting Gravatar...
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
Left by dru on Mar 14, 2007 11:44 AM

# re: More thoughts on Equals()
Requesting Gravatar...
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 :)
Left by Tim Hibbard on Mar 14, 2007 11:53 AM

# re: More thoughts on Equals()
Requesting Gravatar...
It's all good in the hood. :)
Left by dru on Mar 14, 2007 8:48 PM

Your comment:
 (will show your gravatar)

Copyright © Tim Hibbard | Powered by: