Search code examples
c#castingoperator-overloadingimplicit-conversionginac

Operator-function + with two implicit casts doesn't work


I'm trying to port some parts from ginac (www.ginac.de) to C#. But I encountered this:

class Program {

static void Main(string[] args) {

        symbol s = new symbol();          
        numeric n = new numeric();

        ex e = s + n; // "Operator + doesn't work for symbol, numeric"
    }
}

class ex {
    //this should be already be sufficient:
    public static implicit operator ex(basic b) {
        return new ex();
    }
    //but those doesn't work as well:
    public static implicit operator ex(numeric b) {
        return new ex();
    }
    public static implicit operator ex(symbol b) {
        return new ex();
    }

    public static ex operator +(ex lh, ex rh) {
        return new ex();
    }
}
class basic {      
}
class symbol : basic {
}
class numeric : basic {
}

The correct order should be: implicitly cast symbol->basic->ex, then numeric->basic->ex and then use the ex operator+(ex,ex) function.

In which order is the lookup for implicit casting functions and operator functions done? Is there any way around this?


Solution

  • Cast the first operand to "ex". The first operand of the + operator will not be implicitly cast. You need to use an explicit cast.

    The + operator actually determines its type from the first operand, which is symbol in your case. When the first operand is an ex, then the ex+ex will attempt the implicit cast of the second operand.