I would like to be sure. If I apply == operator between two operands of type class, it returns true when both variables points at the same object? Also like in string class, to check equality based on e.g. some value, I would need to override that operator. IS that true?
5 Answers
The default implementation of == uses referential equality on reference types, i.e. objects are equal if and only if they are the same instance.
You can overload the == and != operator. If you do that, for consistency you should also override Equals and GetHashCode(). If you don't also override those you will only get the correct equality using == and != but many other uses such as Dictionary or HashSet will still use referential equality.
You always need to overload == and != together. Usually I write the comparison itself in == and express the other comparisons using ==.
public static bool operator ==(MyClass x, MyClass y) { } public static bool operator !=(MyClass x, MyClass y) { return !(x==y); } public override bool Equals(object obj) { if((obj==null)||(obj.GetType()!=typeof(MyClass)) return false; return this==(MyClass)obj; } public override int GetHashCode() { } And you should consider making the class immutable. Equality mustn't change while the object is inside a HashSet or Dictionary, and making it completely immutable saves a lot of trouble. And since you can only achieve value semantics using immutable classes and the goal of overriding equality is getting value semantics you basically need immutability.
2 Comments
equals snippet.For the second question, to give == a special meaning, you do indeed need to overload (not override) the operator (and != at the same time):
public class Test { public static bool operator ==(Test t1, Test t2) { // Insert logic here, being careful of the possibility of // t1 and t2 being null. And don't just use if (t1 == null) // - it will recurse! } public static bool operator !=(Test t1, Test t2) { // Usual way of implementing return !(t1 == t2); } } If you're overloading == you should almost certainly also:
- Implement
IEquatable<T> - Quite possibly make your class sealed and immutable (equality which can change is troubling)
- Override Equals(object) and GetHashCode
Comments
This is a full explanation from MSDN.
And yes it does compare references of class/object instances.