In C#, operator overloading is supported as syntax sugar of static method calling.
For example, operator+ will be converted to the static method op_Addition.
BTW, the following code is valid:
using System;
public struct Container<T>
{
public T Value { get; }
public Container(T value) => Value = value;
public static Container<T> operator+(Container<T> lhs, Container<T> rhs)
=> new Container<T>(FieldProvider<T>.Current.Add(lhs.Value, rhs.Value));
/* is equivalent to :
public static Container<T> op_Addition(Container<T> lhs, Container<T> rhs)
=> new Container<T>(FieldProvider<T>.Current.Add(lhs.Value, rhs.Value));
*/
}
public static class Program
{
public static void Main()
{
var a = new Container<int>(1);
var b = new Container<int>(2);
var c = a + b;
/* is equivalent to:
var c = Container<int>.op_Addition(a, b);
*/
Console.WriteLine(c.Value);
}
}
but the following code is not valid:
using System;
public struct Container<T>
{
public T Value { get; }
public Container(T value) => Value = value;
public static Container<int> operator+(Container<int> lhs, Container<int> rhs)
=> new Container<int>(FieldProvider<int>.Current.Add(lhs.Value, rhs.Value));
}
public static class Program
{
public static void Main()
{
var a = new Container<int>(1);
var b = new Container<int>(2);
var c = a + b;
Console.WriteLine(c.Value);
}
}
although the following code is valid:
using System;
public struct Container<T>
{
public T Value { get; }
public Container(T value) => Value = value;
public static Container<int> op_Addition(Container<int> lhs, Container<int> rhs)
=> new Container<int>(FieldProvider<int>.Current.Add(lhs.Value, rhs.Value));
}
public static class Program
{
public static void Main()
{
var a = new Container<int>(1);
var b = new Container<int>(2);
var c = Container<int>.op_Addition(a, b);
Console.WriteLine(c.Value);
}
}
Like this, type-closed generic static method is available but such a operator is prohibited now.
In this proposal I suggest to allow operator overloading for type-closed generics such as 2nd code.
Maybe related to #1315.
In C#, operator overloading is supported as syntax sugar of static method calling. For example,
operator+
will be converted to the static methodop_Addition
.BTW, the following code is valid:
but the following code is not valid:
although the following code is valid:
Like this, type-closed generic static method is available but such a operator is prohibited now. In this proposal I suggest to allow operator overloading for type-closed generics such as 2nd code.