Explicit cast in expression tree?

Viewed 832

Consider the MyDecimal class below. In C# we can cast it to an integer thanks to the implicit decimal operator:

int i = (int)new MyDecimal(123m);

How do you produce the equivalent code in an expression tree?

When using Expression.Convert (.NET 4.5.1) it immediately fails with No coercion operator is defined between types 'System.Int32' and 'MyDecimal'. It seems to only consider implicit cast operators.

try
{
    var param = Expression.Parameter(typeof(int), null);
    var convert = Expression.Convert(param, typeof(MyDecimal));
}
catch (Exception ex)
{
}

MyDecimal class:

public class MyDecimal
{
    private readonly decimal value;

    public MyDecimal(decimal value)
    {
        this.value = value;
    }

    public static implicit operator decimal(MyDecimal myDecimal)
    {
        return myDecimal.value;
    }

    public static implicit operator MyDecimal(decimal value)
    {
        return new MyDecimal(value);
    }
}
1 Answers
Related