6

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(?).

MByD
  • 135,866
  • 28
  • 264
  • 277
Dhananjay
  • 3,673
  • 2
  • 22
  • 20

4 Answers4

7

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;
Community
  • 1
  • 1
Malmi
  • 387
  • 3
  • 8
  • 1
    To be specific, those postfixes are for double, float, long, and [decimal](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/decimal) respectively. There are also postfixes for unsigned ints and longs (`U` and `UL`). – Aaron Franke Apr 01 '19 at 23:24
5

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 or u, it has the first of these types in which its value can be represented: uint, ulong.
  • If the literal is suffixed by L or l, 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, or lu, it is of type ulong.

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.

Community
  • 1
  • 1
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
4

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;
Joey
  • 344,408
  • 85
  • 689
  • 683
  • then its good to write short s =0; atleast it is shorter version. – Dhananjay Mar 16 '12 at 03:24
  • Yes, you can. But you probably knew that before. I got the impression that your confusion stems from why the compiler won't treat `0` as short automatically. – Joey Mar 16 '12 at 06:43
2

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;
Saeb Amini
  • 23,054
  • 9
  • 78
  • 76