- Home /
c# How does an == decide if two objects are the same?
Hey guys,
I've had a bit of a google around for the answer to this question, maybe I don't know the terms I need in order to find the answer so I'm going to ask on here. Please forgive me if this has been answered somewhere before.
I know that most things are passed around by reference in unity [[source]][1] so I wonder if it is the memory address that is compared; that way it would return true if the two references referred to the same instance of a class. Perhaps (as I do) you might want to compare the values of an object, would comparing two instances of a class return true if they were different instances but had the same values?
I realise I could test both of these cases but I'm interested in the logic that lies behind a comparison so I can make a more informed decision about comparisons when I'm coding.
Thanks in advance for any help you can provide me.
[1]: http://answers.unity3d.com/questions/225286/how-do-i-know-whether-variable-is-pass-by-value-or.html
Answer by Jeff-Kesselman · May 21, 2014 at 07:37 PM
The Object class has a virtual method called Equals.
BY default, that method calls a non-virtual method called ReferenceEquals. You can read about ReferenceEquals here but yes, basically, it checks the location in memory. http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx
HOWEVER any class can override Equals and many do. So you need to check the documentation for the class in question.
So if I wanted to compare my class by value, I could override with my own equals method in order to do so?
Be careful here - Unity also overrides the equality operator for anything derived from UnityEngine.Object (including ScriptableObject, GameObject, and $$anonymous$$onoBehaviour) - this overload causes destroyed objects to compare as equal to null until they're actually disposed.
If you overload equals, you may interfere with this behaviour.
If you need a custom comparison for a subclass of UnityEngine.Object, it may be safer to define your own IsIdenticalTo(other) method or something similar. That way you can be explicit about when your comparison should be used ins$$anonymous$$d of the usual behaviour.
Interesting, okay, given that writing my own is no more difficult, I'll just do that. Thanks for the advice.
The other issue with overriding equals to be value based to be aware of is that many collections use it to deter$$anonymous$$e equality so an override may produce unwanted collection results. For instance a Set would only allow one object with any given value. If used as a key in a Dictionary, it would match on value not on object which, again, may not be what you want. If you call Remove(object) it will remove the first object with the same value, etc..
Your answer
Follow this Question
Related Questions
Store reference to array as variable 2 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers