1

Possible Duplicate:
No implicit int -> short conversion in ternary statement

So I understand the fundamentals of type conversion and inference of types in the C# ternary operator, thanks mostly to Eric Lippert's answer to this question. But the thing I'm still not understanding is what I have below.

I guess I understand that C# is assuming the zero is an int because that's somehow the default, so an error is thrown when I try to assign an int to a short variable:

short recordNumber = Convert.IsDBNull(dr["record_number"]) ? 0 
    : Convert.ToInt16(dr["record_number"]);

This error gets thrown:

Cannot implicitly convert type 'int' to 'short'. 
An explicit conversion exists (are you missing a cast?)

This is what VS10 is looking for:

short recordNumber = Convert.IsDBNull(dr["record_number"]) ? (short)0 
    : Convert.ToInt16(dr["record_number"]);

What I'm trying to understand is why is 0 chosen to be int rather than short? If it was chosen to be a short then that would make it more universally "assignable". Is there some reason for this that I'm missing?

Community
  • 1
  • 1
DanM7
  • 2,203
  • 3
  • 28
  • 46
  • Thanks @JonB, I dug and dug and couldn't find a similar question. But in that question, the answer (even though it's a good one from Jon Skeet) is more saying how to fix it. I'm trying to find out why it was chosen that 0 would be `int` over `short`. Different enough? I'm not sure... I'll let the community decide and close if needed. – DanM7 Nov 21 '12 at 16:28
  • @JonB I also changed the subject as it could have been misleading and wasn't focused on the basis of my question. I understand why it causes the error, I want to know zero is `int` and not `short`. – DanM7 Nov 21 '12 at 16:57
  • Take a look at Eric's blog post, linked from the comments of that question: http://blogs.msdn.com/b/ericlippert/archive/2006/05/24/type-inference-woes-part-one.aspx "Since the types are not the same, and literal zero goes to short, and s goes to int, no expression type can be determined and we report an error" – Richard Deeming Nov 21 '12 at 17:16

0 Answers0