Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The compiler has an implicit conversion from a <em>constant</em> expression to various primitive types (so long as the value is within the appropriate range), but here the expression isn't constant - it's just an int expression. It's pretty much the same as:</p> <pre><code>short s; s = CallSomeMethodReturningInt32(); </code></pre> <p>as far as the compiler is concerned.</p> <p>There are two options - you could cast the whole expression, or cast each of the latter two operands:</p> <pre><code>short s = (EitherTrueOrFalse()) ? (short) 0 : (short) 1; </code></pre> <p>to make the overall expression type <code>short</code>. In this particular case, it's a pity that there isn't a numeric literal suffix to explicitly declare a <code>short</code> literal. Apparently the language designers did consider this, but felt it was a relatively rare situation. (I think I'd probably agree.)</p> <p>The part about implicit constant conversions is from the C# 3.0 spec section 6.1.8:</p> <blockquote> <p><strong>6.1.8 Implicit constant expression conversions</strong></p> <p>An implicit constant expression conversion permits the following conversions:</p> <ul> <li>A <em>constant-expression</em> (§7.18) of type <code>int</code> can be converted to type sbyte, <code>byte</code>, <code>short</code>, <code>ushort</code>, <code>uint</code>, or <code>ulong</code>, provided the value of the <em>constant-expression</em> is within the range of the destination type.</li> <li>A <em>constant-expression</em> of type <code>long</code> can be converted to type <code>ulong</code>, provided the value of the <em>constant-expression</em> is not negative.</li> </ul> </blockquote>
 

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