Why C# compiler doesn't call implicit cast operator?

That is an interesting question... it works with Decimal, for example, but not TimeSpan, which are both proper .NET types (unlike float etc that are primitives) and both have an + operator. Curious!

Of course, you can twist the arm with:

Money m3 = (Money)m1 + (Money)m2;

And it you just use Nullable<T> it'll work for free, of course - plus you get the compiler + runtime (boxing) support. Is there a reason not to use Nullable<T> here?

I'll look at the spec; in the interim, you might think about promoting the operator to the MyNullable<T>; with regular Nullable<T>, the C# compiler provides "lifted" operators for those supported by the type, but you can't do that yourself. The best you can do is offer all the obvious ones and hope the type supports it ;-p To access operators with generics, see here, available for free download here.

Note you'd probably want to apply the appropriate "lifted" checks - i.e.

x + y => (x.HasValue && y.HasValue)
          ? new MyNullable<T>(x.Value + y.Value)
          : new MyNullable<T>();

Update

The different handling looks to relate to 14.7.4 (ECMA 334 v4) "Addition operator", where it is pre-defined for a range of types including decimal (so that was a bad test by me), since by 14.2.4 (same) "Binary operator overload resolution", the pre-defined operators do get special mention. I don't claim to understand it fully, though.


Marc is on the right lines - it's section 7.2.4 in the C# 3.0 spec - Binary Operator Overload Resolution.

Basically the steps are:

  • We need to resolve the implementation for "X + Y" where X and Y are both MyNullable<Money>.
  • Looking at section 7.2.5 (candidate user-defined operators) we end up with an empty set, as MyNullable<T> doesn't overload +.
  • Back in 7.2.4 the set of candidate operators is the built-in set of binary operators for +, i.e. int+int, decimal+decimal etc.
  • Overload resolution rules in 7.4.3 are then applied. When we're doing MyNullable<int> + MyNullable<int> this works because of the implicit conversions of each argument to int - but when we're doing MyNullable<Money> + MyNullable<Money> it doesn't work because Money + Money isn't in the set of candidate operators.