1

Consider the following code:

var x = 32;

The number 32 will fit in within sbyte, byte, short, ushort, etc.

Why does .NET assume this is an int?

Same question for var x = 3.2; .NET assumes double

Matthew Layton
  • 39,871
  • 52
  • 185
  • 313
  • Try `decimal d = 3.2;`, it produces an enlightening error. – H H Mar 16 '16 at 11:04
  • @HenkHolterman - why can the compiler not automatically infer this from the left hand type specifier? - it wouldn't complain if I did uint x = 32; ? – Matthew Layton Mar 16 '16 at 11:06
  • 1
    Possible duplicate of [C# short/long/int literal format?](http://stackoverflow.com/questions/5820721/c-sharp-short-long-int-literal-format) – CodeCaster Mar 16 '16 at 11:08
  • 1
    The number of situations where the compiler *has* a left-hand side to inspect are vastly dwarfed by the number of times it's trying to assess the result type of an expression which will not be stored in any explicit variable. Having different rules depending on whether it's dealing with an assignment or not would make for a more confusing language. So the compiler can only use the types of the subexpressions that make up the expression, to determine it's type. – Damien_The_Unbeliever Mar 16 '16 at 11:23

1 Answers1

4

Why does .NET assume this is an int?

Wrong question/subject. It is the C# compiler that assume this is an int.

Taken from 2.4.4.2 Integer literals:

The type of an integer literal is determined as follows:
If the literal has no suffix, it has the first of these types in which its value can be represented: int, uint, long, ulong.

and from 2.4.4.3 Real literals:

If no real type suffix is specified, the type of the real literal is double.

Another important "trick" of the compiler, that makes this legal:

byte b = 5;

(normally 5 would be an int, and there is no implicit conversion from int to byte), but:

Taken from 6.1.6 Implicit constant expression conversions:

An implicit constant expression conversion permits the following conversions:

  • A constant-expression (Section 7.15) 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.

  • A constant-expression of type long can be converted to type ulong, provided the value of the constant-expression is not negative.

Community
  • 1
  • 1
xanatos
  • 109,618
  • 12
  • 197
  • 280