Reputation: 1168
In what situations would you consider overloading an operator in .NET?
Upvotes: 11
Views: 1977
Reputation: 29157
I think the Framework design guidelines provide some decent advice:
- AVOID defining operator overloads, except in types that should feel like primitive (built-in) types.
- CONSIDER defining operator overloads in a type that should feel like a primitive type.
- DO define operator overloads in structs that represent numbers (such as System.Decimal).
- DO NOT be cute when defining operator overloads.
- DO NOT provide operator overloads unless at least one of the operands is of the type defining the overload.
- DO overload operators in a symmetric fashion.
- CONSIDER providing methods with friendly names that correspond to each overloaded operator.
Upvotes: 16
Reputation: 55082
I did request to close this, but perhaps it can remain open (I tried to change my mind but apparently you can't revoke a close request :P)
I will answer personally: never.
I never think it's a good idea to implement operator overloading. There is only one exception: If I'm writing some sort of collection (it doesn't happen very often) and I want to implement the indexers []
.
In my personal opinion, I do not think it is ever appropriate to be overriding ==
, and other such things. But then again, I do not work in complex fields of maths and finance, where such things may be useful. But I can't speak from experience in that matter (actually, I can in the finance world, and we didn't do it there).
Upvotes: 3
Reputation: 64628
I consider overriding operators i this cases:
Upvotes: 3
Reputation: 158309
I would consider using operator overloading for arithmetic operations on types that represent a logical value. For instance, there have been occasions when I wished that Point
had an overload for the +
and -
operators.
Upvotes: 2
Reputation: 1500525
Equals
IComparable<T>
Nullable<T>
)The golden rule is not to overload operators if the meaning isn't entirely obvious. For example, I think it would be pretty odd to have a + operator on Stream
- it could mean "make a writable T here, so that writes to the result write to both" or it could mean "read one after the other" or probably other things.
In my experience it's pretty rare to overload anything other than == and !=.
Upvotes: 17