Home Dashboard Directory Help

Allow operators for an interface in C# by eldiener


 as External Help for as External

Sign in
to vote
Type: Suggestion
ID: 536835
Opened: 2/26/2010 7:13:45 AM
Access Restriction: Public


In C# in an interface, one should be able to specify both a declaration and an implementation for an operator, which is a static function. This would ease the use of interfaces to provide a more natural syntax. The operator in an interface would normally be made in terms of interface members, which would then be implemented by classes to provide the actual functionality. An example would be:

    interface SomeNumber
    static SomeNumber operator * (SomeNumber first, SomeNumber second) { return(first.multiply(second)); }    
    SomeNumber multiply(SomeNumber other);    
Then when some class implements this interface, it provides an implementation for the 'multiply' function. In functionality dealing with the interface, one could then say 'y = a * b' instead of 'y = a.multiply(b)', where a,b, and y are all of the SomeNumber type. The former syntax, involving operators, provides a much more natural syntax than the latter.

The alternative of having a class which implements the interface provide possible operators, which is the only way in which the above effect can now be done, is much less logical since it is the interface itself which is providing the specification for what it means. Therefore it is the interface which should be allowed to provide the static operator rather than the class implementing the interface. Furthermore when a class which implements the interface provides the static operators, code dealing with the interface itself, as in the 'y = a * b' example above, can not use the operators and will not work,since they are not defined by the interface itself.

In C++/CLI the equivalent functionality above is already allowed, where an interface can create an operator based on its own members. This should therefore also be allowed in C#.
Sign in to post a comment.
Posted by Microsoft on 6/24/2010 at 6:57 PM
Thanks for the great suggestion for Visual Studio!

Supporting operators in interfaces (such as an IArithmetic<T> interface) is a quite common request for VB and C# and the CLR has been looking into adding the support required for interfaces to inherit operators. We can't promise if or when we'll get to this feature, but we'll definitely keep it in mind during planning for the next release!

Alex Turner
Program Manager
Visual Basic and C# Compiler
Posted by Microsoft on 3/1/2010 at 1:33 AM
Thank you for your feedback, we are currently reviewing the feedback you have submitted.
Sign in to post a workaround.