Home > Enterprise >  C# implicit operator generic minus/plus int
C# implicit operator generic minus/plus int

Time:01-04

I have this class in C#:

public class MyClass<A, B> where B : OtherClass<A>
{
    [SerializeField] A _value = default;
        
    public A Value 
    {
        get => _value;
        set => _value = value;
    }

    public static implicit operator A(MyClass<A, B> variable)
    {
        return variable.Value;
    }
}

I'ld really like to being able to do this:

MyClass<int, OtherClass<int>> myVar = new MyClass<int, OtherClass<int>>();
myVar.Value = 5;
myVar -= 3; // this is actually not valid and I wish to make it valid.

Is there a way I don't know to make this?
Tell me if you need any further informations.

CodePudding user response:

No, that's not possible. Since there is no interface for even having an operator -, there is no way to express that A must have an operator -. And with that possibility gone, there is no way to create your own operator - calling A's operator minus.

  •  Tags:  
  • Related