I have an extension class for System.Net.IPAddress and I was wanting to overload the binary operators >, <, ==
but the compiler is telling me that I can't overload those operators inside a static class, which I must have for my other extension methods. Is there a particular reason for this?
Thanks.
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.
These operators cannot be overloaded because if we overload them it will make serious programming issues. For an example the sizeof operator returns the size of the object or datatype as an operand. This is evaluated by the compiler. It cannot be evaluated during runtime.
Explanation: . (dot) operator cannot be overloaded therefore the program gives error.
An overloaded operator (except for the function call operator) cannot have default arguments or an ellipsis in the argument list. You must declare the overloaded = , [] , () , and -> operators as nonstatic member functions to ensure that they receive lvalues as their first operands.
Operators must relate to instances of the type in which they are declared. Since you can't have instances of a static class, it makes no sense to define operators.
There are no "extension operators" in .NET.
For your purposes, consider implementing an IComparer<T>
(covers <
and >
) and / or IEqualityComparer<T>
(covers ==
, or you might just use compare returning 0
; it depends whether you consider "sorts equal" and "equal" as the same).
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