How can I define the operator ==
for instances of my class? I tried like this:
public bool operator == (Vector anotherVector)
{
return this.CompareTo(anotherVector) == 1 ;
}
but it says:
overloadable unary operator expected
You need to mark the method as static
and also you have to implement not equal !=
.
public static bool operator ==(Vector currentVector,Vector anotherVector)
{
return currentVector.CompareTo(anotherVector) == 1 ;
}
You have to implement ==
for two objects.
AND for !=
AND
public static bool operator !=(Vector currentVector,Vector anotherVector)
{
return !(currentVector.CompareTo(anotherVector) == 1) ;
}
See: Guidelines for Overloading Equals() and Operator == (C# Programming Guide)
Overloaded operator == implementations should not throw exceptions. Any type that overloads operator == should also overload operator !=.
Unlike C++, which allows operators to be defined as instance member functions so that the left operand becomes the this
pointer, C# operator overloading is always done as static member functions.
There can be no this
pointer, and both operands are explicit parameters.
public static bool operator==(Vector left, Vector right)
{
return left.CompareTo(right) == 1;
}
(Although this seems semantically incorrect, normally CompareTo
returns zero for equivalence)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With