Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator overloading - why static resolve?

What are the reasons for resolving overloaded operators statically? It seems a strange choice to me - the only advantage I can think of is a small performance gain (but then the JIT may avoid that sometimes as well) at the cost of some rather unintuitive behavior - i.e. I basically have to forward the operator to a virtual function to get the wanted behavior.

Was this just taken over from C++ or are there some other good reasons for this?

like image 931
Voo Avatar asked Dec 15 '11 21:12

Voo


2 Answers

See Eric Lipperts article Why are overloaded operators always static in C#?

Rather, the question we should be asking ourselves when faced with a potential language feature is "does the compelling benefit of the feature justify all the costs?" And costs are considerably more than just the mundane dollar costs of designing, developing, testing, documenting and maintaining a feature. There are more subtle costs, like, will this feature make it more difficult to change the type inferencing algorithm in the future? Does this lead us into a world where we will be unable to make changes without introducing backwards compatibility breaks? And so on.

In this specific case, the compelling benefit is small. If you want to have a virtual dispatched overloaded operator in C# you can build one out of static parts very easily. [...]

It is be possible to support instance based operators but the C# language designer did not see the big gain compared to the efforts needed to make it work correctly.

like image 168
Alois Kraus Avatar answered Oct 03 '22 04:10

Alois Kraus


Consider the case of when overloading the operator for a reference type. It could be null on either side of the operator.

If operators were instance methods, they wouldn't work.

like image 38
Daniel A. White Avatar answered Oct 03 '22 05:10

Daniel A. White