If there is a class Cow
, and it has two instances – cowA
and cowB
– is this accepted?
if (cowA > cowB)
{
}
If so, why?
If there is a class Cow
, and it has two instances – cowA
and cowB
– is this accepted?
if (cowA > cowB)
{
}
If so, why?
If, by accepted, you mean good practice then short answer is: it is not wrong. More specifically if in the context that the objects are used, comparisons (greater than and less than) make intuitive sense then operator overloading is not a bad thing.
On the other hand, if comparisons can have ambiguous meanings then it would be better to use functions with descriptive names which imply specific meaning. At the end of the day, we want code that makes its intent clear to the reader.
This is perfectly acceptable if Cow
overloads the >
operator. It certainly won’t by default, but you can define it!
Operators are just special functions, so if you write one that takes Cow
objects, the compiler/runtime won’t complain.
In the event that Cow had an implicit cast to a numeric type the line would also be valid, though this is pretty unlikely ;)
To overload the >
operator, you would do something like:
public static bool operator < (Cow x, Cow y)
{
return x.Age < y.Age;
}
Obviously I made up the comparison logic :)
Note that if you do this, you are required to also overload >
. See MSDN