Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't C# permit overloading operator()?

This question comes from a previous discussion on C++ Functors (Do functors have an equivalent in C#?).

Why doesn't C# allow overloading operator()?

You can overload operators but what advantage would there be if operator() could also be overloaded?

like image 903
4thSpace Avatar asked Dec 21 '25 02:12

4thSpace


1 Answers

C# has operator(), which it spells Invoke.

Anytime you define a delegate type, you are defining a class with a method named Invoke and can use function call syntax with instances of that class, which will result in a call to Invoke. Like operator(), C# delegate Invoke methods can have almost any function signature.

Unlike C++ operator(), C# doesn't allow defining arbitrary other members on the same class that defines Invoke. You could say that C# is enforcing the Single Responsibility Principle here. This isn't a major limitation, however, because C# delegates get wired to another object that provides storage of state for the function object.

A more severe (in the sense that there is no simple workaround) limitation on C# Invoke compared to C++ operator() is that C# delegate Invoke methods cannot be overloaded nor polymorphic. This is a consequence of the need to forward the call to a method on another object, but it prevents some usage scenarios possible with C++ custom functors.

It would be interesting to see what happens if you defined an overloaded Invoke method using MSIL. Certainly you would confuse the C# compiler if you tried to use such a delegate class, and probably also the CLR runtime. So this is a curiosium rather than a practical approach.

C++ std::function is quite similar to C# delegate types in capability and limitations. It also forwards invocations, and isn't polymorphic on the call signature. Ditto for C++11 lambdas, although C++14 lambdas will allow templated operator() and call-site type polymorphism (unlike C# lambdas which allow only point-of-definition polymorphism).

like image 185
Ben Voigt Avatar answered Dec 23 '25 20:12

Ben Voigt