kiss my armpit
kiss my armpit

Reputation: 3519

Why can we assign a literal integer of 32 bit to a variable of type short without casting?

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

Answers (1)

Jon
Jon

Reputation: 437634

Because the specification allows for that in section 6.1.9:

A constant expression of type int can be converted to sbyte, byte, short, ushort, uint, or ulong, 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

Related Questions