I am practicing a C# 11&12 new features so I have written an interface and a class like this:
public interface IHello<T> where T: class
{
static abstract IHello<T> operator +(IHello<T> left, IHello<T> right);
public string Value { get; }
}
public class Hello(string value) : IHello<string> // Error CS0535 'Hello' does not implement interface member 'IHello<string>.operator +(IHello<string>, IHello<string>)'
{
public string Value { get; } = value;
public static IHello<string> operator +(Hello left, IHello<string> right)
{
return new Hello(left.Value + right.Value);
}
}
However, on the class definition I get an error:
Error CS0535 'Hello' does not implement interface member 'IHello.operator +(IHello, IHello)'
If I change the operator signature to directly match the IHello<string> interface being implemented:
public class Hello(string value) : IHello<string>
{
public string Value { get; } = value;
public static IHello<string> operator +(IHello<string> left, IHello<string> right) // Error CS0563 One of the parameters of a binary operator must be the containing type
{
throw new NotImplementedException();
}
}
The error then becomes:
Error CS0563 One of the parameters of a binary operator must be the containing type
Is there a way to reconcile between the two and implement this interface?
Taking the implementation type as a type paramter in the interface allows you define on operator parameter as an implementation type:
Usage:
The newer static abstract math stuff does this extensively. Check the type parameters in the interfaces of
INumber<TSelf>.