Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy C# compiler doesn't call implicit cast operator?
    text
    copied!<p>Suppose we have following type:</p> <pre><code>struct MyNullable&lt;T&gt; where T : struct { T Value; public bool HasValue; public MyNullable(T value) { this.Value = value; this.HasValue = true; } public static implicit operator T(MyNullable&lt;T&gt; value) { return value.HasValue ? value.Value : default(T); } } </code></pre> <p>And try to compile following code snippet:</p> <pre><code>MyNullable&lt;int&gt; i1 = new MyNullable&lt;int&gt;(1); MyNullable&lt;int&gt; i2 = new MyNullable&lt;int&gt;(2); int i = i1 + i2; </code></pre> <p>This snipped compiled well and without errors. i1 and i2 casts to integer and addition evaluated.</p> <p>But if we have following type:</p> <pre><code>struct Money { double Amount; CurrencyCodes Currency; /*enum CurrencyCode { ... } */ public Money(double amount, CurrencyCodes currency) { Amount = amount; Currency = currency; } public static Money operator + (Money x, Money y) { if (x.Currency != y.Currency) // Suppose we implemented method ConvertTo y = y.ConvertTo(x.Currency); return new Money(x.Amount + y.Amount, x.Currency); } } </code></pre> <p>Try to compile another code snippet:</p> <pre><code>MyNullable&lt;Money&gt; m1 = new MyNullable&lt;Money&gt;(new Money(10, CurrenciesCode.USD)); MyNullable&lt;Money&gt; m2 = new MyNullable&lt;Money&gt;(new Money(20, CurrenciesCode.USD)); Money m3 = m1 + m2; </code></pre> <p>And now the question, why compiler generate "<em>error CS0019: Operator '+' cannot be applied to operands of type 'MyNullable&lt;Money&gt;' and 'MyNullable&lt;Money&gt;'</em>"?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload