Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Some C# 11&12 Practicing failed

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?

like image 780
mz1378 Avatar asked Feb 07 '26 13:02

mz1378


1 Answers

Please note that the main purpose of static virtual members in interfaces is:

Once you've defined interfaces with static members, you can use those interfaces as constraints to create generic types that use operators or other static methods.

However, what you are doing now is trying to define the addition of a class, and the starting points of them are different. Don't confuse them.

public class Hello(string value) : IHello<string>
{
    public string Value { get; } = value;

    // the addition of a class
    public static Hello operator +(Hello left, Hello right)
        => new Hello(left.Value + right.Value);

    // static virtual members
    static IHello IHello.operator +(IHello left, IHello right)
        => left is Hello lh && right is Hello rh ? lh + rh : throw new ArgumentException();
}

public interface IHello
{
    static abstract IHello operator +(IHello left, IHello right);
}

public interface IHello<T> : IHello
{
    public T Value { get; }
}

And the abstract operator should be used in a generic class:

public class Test<T> where T : IHello
{
    public static void Add(T u1, T u2)
        => Console.WriteLine(u1 + u2);
}
like image 79
shingo Avatar answered Feb 09 '26 08:02

shingo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!