Why is it necessary to reload operators?

I wanted to overload the statement in the class and make it private so that it could be used only from the class.
However, when I tried to compile, I received the error message "User statement ... must be declared static and public:

Why should they be publicly available?

+1
source share
1 answer

To answer half your question, you can see Eric Lippert's blog post.

Why are overloaded operators always static in C #?

Rather, the question we must ask ourselves when confronted with a potential language feature is "the inherent benefit of a function justifies all the costs?" And the costs are significantly more than just the mundane dollar costs of designing, developing, testing, documenting and maintaining a function. There are more subtle costs, for example, will this feature make it difficult to change the type of algorithm to determine in the future? Does this lead us into a world where we cannot make changes without introducing backward compatibility gaps? And so on.

In this particular case, the indisputable advantage is small. If you want to have a virtual dispatched overloaded statement in C #, you can build one of the static parts very easily. For instance:

public class B { public static B operator+(B b1, B b2) { return b1.Add(b2); } protected virtual B Add(B b2) { // ... 

And you have it. Thus, the benefits are small. But the costs are big. C ++ style instance operators are weird. For example, they break symmetry. If you define a + operator that accepts C and int, then c + 2 is legal, but 2 + c is not, and this greatly violates our intuition about how the addition operator should work.

The other part for your question is: why should they be publicly available.

I could not find any genuine source, but IMO, if they are not public and can only be used inside the class, then this can be done using a simple private method, and not with an overloaded operator,

You can see the RB Whitaker blog post

Operator Overload

All operator overloads must be public and static, which should be because we want to have access to the operator throughout and since it refers to the class as a whole, and not to any specific instance of the class.

0
source

Source: https://habr.com/ru/post/947549/


All Articles