Reputation: 3519
In my understanding literal integers belong to System.Int32
by default. If so why can we assign a literal integer of type System.Int32
to short x
without casting?
short x = 1;//compilable
Why don't we need to use casting as follows?
short x = (short)1;
Upvotes: 0
Views: 98
Reputation: 437634
Because the specification allows for that in section 6.1.9:
A constant expression of type
int
can be converted tosbyte
,byte
,short
,ushort
,uint
, orulong
, provided the value of the constant expression is within the range of the destination type.
The 1
is indeed a constant expression of type int
because (section 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
.
Upvotes: 4