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