Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override the == operator

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

like image 835
user2128702 Avatar asked Dec 17 '13 17:12

user2128702


2 Answers

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 !=.

like image 126
Habib Avatar answered Oct 06 '22 01:10

Habib


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)

like image 36
Ben Voigt Avatar answered Oct 05 '22 23:10

Ben Voigt