Reputation: 42260
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
Upvotes: 1
Views: 53
Reputation: 111860
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.
Upvotes: 4