Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Best to override Equals() or to overload == operator?

Status
Not open for further replies.

NeilTrain

Programmer
May 27, 2003
275
0
0
US
I guess the topic title says it all.

I have a simple class, with two strings and a date time, and would like to prevent duplicates from appearing in a collection, so need to do a quick compare.

Is there a reason Equals() exists when we have the ++ operator? Whats the difference and which is the preferred to use?
 
==" checks for reference equality, but ".Equals(obj)" can be overridden to check for attribute equality.

My guess is that you want to override .Equals.

Andrew
 
Yup. You would override .Equals().

An alternative would be to implement IComparable, which would look like this for comparing against an Id value:
Code:
public class Widget : IComparable
{
   override public int CompareTo(object obj)
   {
      // Anything is greater than null
      if( null == obj )
         return 1;

      Widget w = obj as Widget;
      if( null == w )
         throw new ArgumentException("object must be a Widget");

      return this.Id.CompareTo( w.Id );
   }
}

Chip H.

____________________________________________________________________
Donate to Katrina relief:
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top