3

I'm using MS Visual Studio Enterprise 2015 and there's a quirky issue I found. Now, I'm not asking for how to fix the error that arises, but I am wondering why C# is behaving in this manner.

This snippet comes from C# Interactive, but it behaves the same in the editor as well:

short num;
num = 0
//num = 0
num = 4
//num = 4
num = true ? 1 : 2
//num = 1
num = false ? 1 : 2
//num = 2
bool flag = true;
num = flag ? 1 : 2

The last line results in the error:

(1,7): error CS0266: Cannot implicitly convert type 'int' to 'short'. An explicit conversion exists (are you missing a cast?)

Basically, there's no problem assigning numbers to a short, like 0 or 4, and there's no problem literally interpreting ternary either until you give it a variable condition. So what's the deal?

maccettura
  • 10,514
  • 3
  • 28
  • 35
Joe
  • 233
  • 1
  • 5
  • 9
    May want to read [this answer](https://stackoverflow.com/a/1672789/2457029) – maccettura Oct 03 '17 at 20:51
  • 5
    This question has been asked literally hundreds, maybe thousands of times on this site. (Which indicates that perhaps the error message ought to be more explanatory.) – Eric Lippert Oct 03 '17 at 20:55
  • There is a broader set of _implicit_ conversions for constants, see [Implicit constant expression conversions](https://msdn.microsoft.com/en-us/library/aa691286.aspx) in the C# Language Specification, than the set of _implicit_ conversions for non-constants. For constants, the compiler checks if the value is in range and allows implicit narrowing conversions from `int` to e.g. `short`. For non-constants, it is not allowed (you can try with an _explicit_ conversion (cast syntax), but that is another story). The expression `flag ? 1 : 2` is not a constant. – Jeppe Stig Nielsen Oct 03 '17 at 21:13
  • ... unless you make `flag` a `const`, as in `const bool flag = true;`. – Jeppe Stig Nielsen Oct 03 '17 at 21:14
  • Oops, my link "Implicit constant expression conversions" does not work. It is not so easy to link the C# spec. The section is quoted in [this answer by Damien_The_Unbeliever](https://stackoverflow.com/a/12371655/1336654). – Jeppe Stig Nielsen Oct 03 '17 at 21:21

0 Answers0