0

In assumption C# was strongly typed I was a little supprised about the following:

short (C# Reference) https://msdn.microsoft.com/nl-nl/library/ybs77ex4.aspx

Does not compile: short x = 6, y = 45; short z = x + y;

Compiles short x = 6, y = 45; int z = x + y; // result is Struct.Int32

Compiles short x = 6, y = 45; var z = x + y; // var is Struct.Int32

Compiles short x = 6, y = 45; var z = (short)(x + y); // result Struct.Int32 is cast to struct.Int16

Then Resharper suggested as follows and compiles:

        const short a = 6;
        const short b = 45;
        short c = a + b; // result is Struct.Int16 without any casting

although when var is used

        const short a = 6;
        const short b = 45; 
        var c = a + b; // var result is Struct.Int32 not Struct.Int16

What I do not get is why the operation can be stored in short when using const short and not when using short as variable. Secondly when var is used on operation of const short it also results into int and not short what imo means c# secretly casts it when short is stricly defined.

Can anyone elaborate why this is designed as it is?

  • It isn't only for `short`. even `byte`, `sbyte`, `short`, `ushort` do the same. – xanatos Mar 31 '17 at 13:19
  • not really int.MaxValue + int.MaxValue gives overflow, short.MaxValue + short.MaxValue gives cast error... so that takes away the secretly casting thing. no longer being a secret. Although does not explain why its designed diffrently :) – Edward Pieper Mar 31 '17 at 13:19
  • 2
    To answer the part of your question that isn't answered by the duplicate: The reason that the `short c = a + b;` compiles OK is because the compiler is adding `a` and `b` at compile time, and knows that the result fits into a short. If you change the initialisation of `a` and `b` to `= 20000;` you'll get a compile error at `short c = a + b;` because the compiler will have converted the result of `a + b` to an `int` (since it would overflow a `short`). – Matthew Watson Mar 31 '17 at 13:26
  • The "some" cases is indeed the diffrence from the other question. Seems compile time its casted, runtime it is not casted and requires casting. It's not something C# reference explained. – Edward Pieper Mar 31 '17 at 13:39
  • 2
    It's covered in the latest C# standard in section `6.1.9 Implicit constant expression conversions`: *"A constant-expression (§7.19) of type int can be converted to type sbyte, byte, short, ushort, uint, or ulong, provided the value of the constant-expression is within the range of the destination type."* Note that the result of `a + b` when `a` and `b` are both `short` is actually of type `int`. – Matthew Watson Mar 31 '17 at 13:51

0 Answers0