Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator overloading and different types

Tags:

c#

I have a class Score which is going to be heavily used in comparisons against integers. I was planning on overloading the == operator to enable these comparisons as per the code below ?

public class Score
{
    public Score(int score) {
        Value = score;
    }

    public static bool operator ==(Score x, int y) {
        return x != null && x.Value == y;
    }

    public static bool operator ==(int y, Score x)
    {
        return x != null && x.Value == y;
    }
}

Is this a sensible use of operator overloading ?

Should I be providing overloads for the LH and RH sides of the operators to allow the usage to be symmetrical ?

like image 444
Adrian Russell Avatar asked Aug 14 '11 03:08

Adrian Russell


2 Answers

I do think this is a strange situation to use an operator overload, but it is your call.

However, my main point is that if you overload == you will also be required to overload !=

If you then overload !=, the part where you compare x to check that it is not null using x != null will cause, the == operator to call the != operator. This isn't a problem in itself, as long as this doesn't then use a == comparison, as you will have a recursive set of calls, leading to a stack-overflow.

However since a lot of people when overloading != implement it as 'not ==' - in your case this will cause a stack overflow.

Solution: particularly in overloading ==, != and Equals(), its best to use use Object.ReferenceEquals(x, null); when comparing to null.

like image 64
iandotkelly Avatar answered Nov 15 '22 17:11

iandotkelly


I might go ahead and define an implicit conversion from int to Score, so that when you deal with equality, you only need to deal with a single type.

public static implicit operator Score(int value)
{
    return new Score { Value = value }; // or new Score(value);
}
// define bool operator ==(Score score1, Score score2)

// elsewhere 
Score score = new Score { Value = 1 };
bool isScoreOne = (score == 1);

And while you're defining your own == operator, do remember to go ahead and define !=, and override Equals and GetHashCode.

like image 33
Anthony Pegram Avatar answered Nov 15 '22 18:11

Anthony Pegram