Ability to use operators as conditions for generics

Topics: C# Language Design
Nov 14, 2014 at 7:35 AM
Edited Nov 14, 2014 at 7:40 AM
Is it possible to enable checking implementation of operators as conditions for a generic types,

e.g.

public static T Function<T>(T value1, T value2) where T: operator *, operator -
{
   return value1 * 2 - value2;
}

public static IEnumerable<T> Sort<T>(this IEnumerable<T> list) where T: operator >
{
    //sort using '>' operator to compare values
}
Nov 14, 2014 at 11:19 AM
That would require constraints to be on the type and, as it is now, you might look at it as constraints being only on instances.

As to the particular case of the > operator, that is covered by System.IComparable and System.IComparable<T>. The same for = with System.IEquatable<T>.

Probably the right solution is on similar interfaces for other operators.
Developer
Nov 14, 2014 at 2:47 PM
ruwancw wrote:
Is it possible to enable checking implementation of operators as conditions for a generic types,

e.g.

public static T Function<T>(T value1, T value2) where T: operator *, operator -
{
   return value1 * 2 - value2;
}

public static IEnumerable<T> Sort<T>(this IEnumerable<T> list) where T: operator >
{
    //sort using '>' operator to compare values
}
That would require either a modification to the CLR or new calling conventions for such methods (e.g. passing the operators as delegates).

But sure, such a language extension would be possible.
Nov 14, 2014 at 3:07 PM