In c# when i say :
var s = 0;
what should be type of s
? it makes it int32
. then seems like var
is not usable for types like short
and others(?).
In c# when i say :
var s = 0;
what should be type of s
? it makes it int32
. then seems like var
is not usable for types like short
and others(?).
Look at this post here at StackOverflow.
You can specify a postfix for all numbers.
var i = 0;
var d = 0d;
var f = 0f;
var l = 0L;
var m = 0m;
As per the C# language standard, specifically §2.4.4.2 on 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
.
The first rule is all that needs to be applied here. The literal 0
has no suffix and can be represented as type int
(or, in BCL terms, Int32
), so that's the type it has.
As you can infer from the above, to change the type of a literal, you can append a suffix to it. For example, the literal 0u
will be of type uint
. Alternatively, you could explicitly cast the literal to a different type; for example: (short)0
would cause the compiler to treat the literal as a short
.
From the specification (§ 2.4.4.2):
If the literal has no suffix, it has the first of these types in which its value can be represented:
int
,uint
,long
,ulong
.
So smaller types are not automatically inferred. You can add a cast to force such a smaller type:
var s = (short)0;
The C# compiler infers the type to be Int32
. And you cannot implicitly cast it to a short
or byte
because they are smaller in size and you could lose data.
If you'd like the compiler to infer decimal
you can:
var s = 0M;