Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two instances of a class

I have a class like this

public class TestData
{
   public string Name {get;set;}
   public string type {get;set;}

   public List<string> Members = new List<string>();

   public void AddMembers(string[] members)
   {
      Members.AddRange(members);
   }   
}

I want to know if it is possible to directly compare to instances of this class to eachother and find out they are exactly the same? what is the mechanism? I am looking gor something like if(testData1 == testData2) //Do Something And if not, how to do so?

like image 675
Saeid Yazdani Avatar asked Dec 06 '11 12:12

Saeid Yazdani


People also ask

How do you compare two objects in a class?

In Java, the == operator compares that two references are identical or not. Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables). Objects are identical when they share the class identity.

Can you compare two objects of the same class?

This can occur through simple assignment, as shown in the following example. Value equality means that two objects contain the same value or values. For primitive value types such as int or bool, tests for value equality are straightforward.

How do you compare classes in Java?

The compare() method in Java compares two class specific objects (x, y) given as parameters. It returns the value: 0: if (x==y) -1: if (x < y)

How do I compare two instances of Python?

The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and != , except when you're comparing to None .


2 Answers

You should implement the IEquatable<T> interface on your class, which will allow you to define your equality-logic. Actually, you should override the Equals method as well.

public class TestData : IEquatable<TestData>
{
   public string Name {get;set;}
   public string type {get;set;}

   public List<string> Members = new List<string>();

   public void AddMembers(string[] members)
   {
      Members.AddRange(members);
   }   

  // Overriding Equals member method, which will call the IEquatable implementation
  // if appropriate.

   public override bool Equals( Object obj )
   {
       var other = obj as TestData;
       if( other == null ) return false;

       return Equals (other);             
   }

   public override int GetHashCode()
   {
      // Provide own implementation
   }


   // This is the method that must be implemented to conform to the 
   // IEquatable contract

   public bool Equals( TestData other )
   {
       if( other == null )
       {
            return false;
       }

       if( ReferenceEquals (this, other) )
       {
            return true;
       }

       // You can also use a specific StringComparer instead of EqualityComparer<string>
       // Check out the specific implementations (StringComparer.CurrentCulture, e.a.).
       if( EqualityComparer<string>.Default.Compare (Name, other.Name) == false )
       {
           return false;
       }
       ...

       // To compare the members array, you could perhaps use the 
       // [SequenceEquals][2] method.  But, be aware that [] {"a", "b"} will not
       // be considerd equal as [] {"b", "a"}

       return true;

   }

}
like image 73
Frederik Gheysels Avatar answered Oct 21 '22 23:10

Frederik Gheysels


There are three ways objects of some reference type T can be compared to each other:

  1. With the object.Equals method
  2. With an implementation of IEquatable<T>.Equals (only for types that implement IEquatable<T>)
  3. With the comparison operator ==

Furthermore, there are two possibilities for each of these cases:

  1. The static type of the objects being compared is T (or some other base of T)
  2. The static type of the objects being compared is object

The rules you absolutely need to know are:

  • The default for both Equals and operator== is to test for reference equality
  • Implementations of Equals will work correctly no matter what the static type of the objects being compared is
  • IEquatable<T>.Equals should always behave the same as object.Equals, but if the static type of the objects is T it will offer slightly better performance

So what does all of this mean in practice?

As a rule of thumb you should use Equals to check for equality (overriding object.Equals as necessary) and implement IEquatable<T> as well to provide slightly better performance. In this case object.Equals should be implemented in terms of IEquatable<T>.Equals.

For some specific types (such as System.String) it's also acceptable to use operator==, although you have to be careful not to make "polymorphic comparisons". The Equals methods, on the other hand, will work correctly even if you do make such comparisons.

You can see an example of polymorphic comparison and why it can be a problem here.

Finally, never forget that if you override object.Equals you must also override object.GetHashCode accordingly.

like image 23
Jon Avatar answered Oct 22 '22 00:10

Jon