How to compare classes without comparing their values?

PVT123C#

New member
Joined
Dec 28, 2021
Messages
1
Programming Experience
Beginner
I'd like to compare two classes that have the same values, how could I do that, without having to compare the values in the classes? (So thisClass = thasClass, and not thisClass.x = thasClass.x.) The code below is an example of the problem.
C#:
public class SomeClass
 {
     float x;
     public SomeClass(float x)
     {
         this.x = x;
     }
 }

 public class OtherClass : MonoBehaviour
 {
     void Start()
     {
         SomeClass thisClass = new SomeClass(1);
         SomeClass thatClass = new SomeClass(1);
         if (thisClass == thatClass) //this is never true, how would you make it true?
         {
             Debug.Log("classes are the same");
         }
         else
         {
             Debug.Log("classes aren't the same");
         }
     }
 }
 
Last edited by a moderator:
Ultimately you'll have to compare all the values, or else you'll just be comparing two instances of the same class, which will of course always be different as you already noted. But as per the mentioned article you need to do that only once, in the class definition, so you can henceforth use the class's overloaded == operator.
 
Or in c# 9.0 and higher instead of using classes use records. The compiler will supply the equality check code to compare the fields.

NVM. @JohnH's link above says the same thing.
 
I'd like to compare two classes that have the same values, how could I do that, without having to compare the values in the classes?
You're not comparing two classes. You're comparing two objects, i.e. two instances of the same class.
 
Reference semantics...
  • If the both class objects refer to the same memory reference; then their internal content will be the same.
  • If the memory references are different; then you have no recourse but to compare each property value to determine if they're a match.
Record / value semantics...
  • value equality implies that two variables of a record type are equal if their types match and all property and field values match.
 
Back
Top Bottom