I've already gone through question
I understand that, it is necessary to implement ==
, !=
and Equals()
.
public class BOX
{
double height, length, breadth;
// this is first one '=='
public static bool operator== (BOX obj1, BOX obj2)
{
return (obj1.length == obj2.length
&& obj1.breadth == obj2.breadth
&& obj1.height == obj2.height);
}
// this is second one '!='
public static bool operator!= (BOX obj1, BOX obj2)
{
return !(obj1.length == obj2.length
&& obj1.breadth == obj2.breadth
&& obj1.height == obj2.height);
}
// this is third one 'Equals'
public override bool Equals(BOX obj)
{
return (length == obj.length
&& breadth == obj.breadth
&& height == obj.height);
}
}
I assume, I've written code properly to override ==
,!=
,Equals
operators. Though, I get compilation errors as follows.
'myNameSpace.BOX.Equals(myNameSpace.BOX)' is marked as an override
but no suitable method found to override.
So, question is - How to override above operators & get rid of this error?
I think you declared the
Equals
method like this:Since the
object.Equals
method takes an object, there is no method to override with this signature. You have to override it like this:If you want type-safe
Equals,
you can implementIEquatable<BOX>
.As Selman22 said, you are overriding the default
object.Equals
method, which accepts anobject obj
and not a safe compile time type.In order for that to happen, make your type implement
IEquatable<Box>
:Another thing to note is that you are making a floating point comparison using the equality operator and you might experience a loss of precision.
In fact, this is a "how to" subject. So, here is the reference implementation:
REF: https://msdn.microsoft.com/en-us/library/336aedhh(v=vs.100).aspx#Examples
UPDATE: the cast to
(object)
in theoperator ==
implementation is important, otherwise, it would re-execute the operator == overload, leading to a stackoverflow. Credits to @grek40.This
(object)
cast trick is from MicrosoftString
== implementaiton. SRC: https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/string.cs#L643