`DynamicObject` on right hand side of binary operation

29 Views Asked by At

I am trying to make my dynamic class behave as System.Int32 in arithmetic expressions. However, I seem to be unable to handle situation when a dynamic instance is being added to an integer:

dynamic i = new MyInt();
// the following line throws
// Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
// "Operator '+' cannot be applied
// to operands of type 'int' and 'MyInt'":
int result = 1 + i;
class MyInt: DynamicObject {
    public override bool TryConvert(
                            ConvertBinder binder,
                            out object? result) {
        if (binder.Type == typeof(int)) {
            result = 42;
            return true;
        }
        result = default;
        return false;
    }

    public override bool TryBinaryOperation(
                            BinaryOperationBinder binder,
                            object arg, out object? result) {
        if (binder.Operation == ExpressionType.Add) {
            result = 42 + (int)arg;
            return true;
        }
        result = default;
        return false;
    }
}

I do not want to define operator + accepting the first argument of type System.Int32 on MyInt because MyInt is not actually necessarily an integer type - that is determined at runtime, so defining it on the class would be misleading for people using static typing. Is there any other way?

0

There are 0 best solutions below