Reputation: 2121
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
Upvotes: 5
Views: 2049
Reputation: 223257
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 !=.
Upvotes: 9
Reputation: 631
I agree fully with Habib's answer - also +1 it... just don't forget to handle nulls.
public static bool operator ==(Vector left, Vector right)
{
if ((object)left == null)
return (object)left == null;
if ((object)right == null)
return false;
return ...;
}
too big to post as his comment. Hope this helps.
Upvotes: 2
Reputation: 283644
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)
Upvotes: 4