In what situations would you consider overloading an operator in .NET?
This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. For example, we can overload an operator '+' in a class like String so that we can concatenate two strings by just using +.
A user-defined type can overload a predefined C# operator. That is, a type can provide the custom implementation of an operation in case one or both of the operands are of that type. The Overloadable operators section shows which C# operators can be overloaded.
Operator overloading is an example of static polymorphism. You can leverage operator overloading or to add functionality to operators so as to work with user defined types much the same way you work with fundamental data types.
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 !=.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With