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 ?
I might go ahead and define an implicit conversion from
inttoScore, so that when you deal with equality, you only need to deal with a single type.And while you’re defining your own
==operator, do remember to go ahead and define!=, and overrideEqualsandGetHashCode.