Search code examples
c#operator-overloadinglanguage-design

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.


Solution

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