How to specify a short int literal without casting?
Solution 1:
Short answer, No. In C#, there's no letter S
that could be used as var a = 123S
that would indicate that a
is of type short
. There's L
for long
, F
for float
, D
for double
, M
for decimal
, but not S
. It would be nice if there was, but there isn't.
var a = 1M; // decimal
var a = 1L; // long
var a = 1F; // float
var a = 1D; // double
var a = 1; // int
var a = 1U; // uint
var a = 1UL; // ulong
but not
var a = 1S; // not possible, you must use (short)1;
Solution 2:
The question is a bit confusing. Let's define some terms:
A constant expression is (roughly speaking) an expression known to the compiler to be a particular constant value.
A literal is a particular kind of constant expression; 123
and Math.PI
are both constant expressions. The former is a literal, the latter is not.
A constant field is a member of a type that is initialized with a constant expression, and may then be used as a constant expression elsewhere. Math.PI
is an example of a constant field.
A local constant is like a constant field, but scoped to a block. (Just as a local variable is scoped to a block.)
Constant fields and local constants are required to state their type explicitly; there is no "var" form for constants. (The very idea makes one shudder; a "const var" is obviously an oxymoron.)
Local variables are not required to state their type; the type can be inferred from the initializer. Such a local variable is called an "implicitly typed local variable".
So your question is "is there a way to write a literal constant expression of type short that can be used to initialize an implicitly typed local variable of type short?"
No, there is not. You can explicitly type the local variable:
short s1 = 123;
You can explicitly type a local constant:
const short s2 = 123;
Or you can make a constant expression that contains a cast to short:
var s3 = (short)123;
Or you can make a local or field constant and use its name for the initializer of the implicitly typed local:
var s4 = s2;
But there is no way around it; short
has to appear somewhere, either in a field or local declaration or in the cast.
Solution 3:
There is no suffix for the short
data type in C#. If you want an integer literal to be a short, you need to explicitly state the type and provide a literal that is in range.
short s = 123;