Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't operators be overloaded inside a static class?

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.

like image 301
lumberjack4 Avatar asked Feb 11 '10 16:02

lumberjack4


People also ask

Can operator overloading static?

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.

Why we Cannot overload dot operator?

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.

Which operator Cannot be used for operator overloading?

Explanation: . (dot) operator cannot be overloaded therefore the program gives error.

Can operator be overloaded?

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.


1 Answers

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).

like image 153
Marc Gravell Avatar answered Nov 04 '22 16:11

Marc Gravell