C# short/long/int literal format?
In C/C#/etc. you can tell the compiler that a literal number is not what it appears to be (ie., float
instead of double
, unsigned long
instead of int
):
var d = 1.0; // double
var f = 1.0f; // float
var u = 1UL; // unsigned long
etc.
Could someone point me to a list of these? I'm specifically looking for a suffix for short
or Int16
.
Solution 1:
var d = 1.0d; // double
var d0 = 1.0; // double
var d1 = 1e+3; // double
var d2 = 1e-3; // double
var f = 1.0f; // float
var m = 1.0m; // decimal
var i = 1; // int
var ui = 1U; // uint
var ul = 1UL; // ulong
var l = 1L; // long
I think that's all... there are no literal specifiers for short/ushort/byte/sbyte
Solution 2:
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
.- If the literal is suffixed by
U
oru
, it has the first of these types in which its value can be represented:uint
,ulong
.- If the literal is suffixed by
L
orl
, it has the first of these types in which its value can be represented:long
,ulong
.- If the literal is suffixed by
UL
,Ul
,uL
,ul
,LU
,Lu
,lU
, orlu
, it is of typeulong
.
And from §2.4.4.3 Real literals:
If no real type suffix is specified, the type of the real literal is double. Otherwise, the real type suffix determines the type of the real literal, as follows:
- A real literal suffixed by
F
orf
is of typefloat
. For example, the literals1f
,1.5f
,1e10f
, and123.456F
are all of typefloat
.- A real literal suffixed by
D
ord
is of typedouble
. For example, the literals1d
,1.5d
,1e10d
, and123.456D
are all of typedouble
.- A real literal suffixed by
M
orm
is of typedecimal
. For example, the literals1m
,1.5m
,1e10m
, and123.456M
are all of typedecimal
. This literal is converted to a decimal value by taking the exact value, and, if necessary, rounding to the nearest representable value using banker's rounding (Section 4.1.7). Any scale apparent in the literal is preserved unless the value is rounded or the value is zero (in which latter case the sign and scale will be 0). Hence, the literal2.900m
will be parsed to form the decimal with sign0
, coefficient2900
, and scale3
.
Solution 3:
If your variable isn't already a short, you have to cast it explicitly :
Object s = (Int16) 1;
Solution 4:
There isn't one for short. Just use short s = 1;
.