10

Possible Duplicate:
C# short/long/int literal format?

Reading up on the use of var in programming, I'm curious about what var defaults to when it's used for an int type. For example, if I use

var foo = 65535

will the type be ushort or just int? Thanks.

Community
  • 1
  • 1
PiousVenom
  • 6,888
  • 11
  • 47
  • 86
  • 5
    It's probably Int32, seeing as that's sort of the standard. Why don't you find out? `var num = 65535; Console.Write(num.GetType().Name)` – KChaloux Oct 19 '12 at 14:17

2 Answers2

28

Really, what you're asking is What type is given to integer literals in C#?, to which the answer can be found in the specification:

(Section 2.4.4.2 of the 4.0 spec)

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.

If the value represented by an integer literal is outside the range of the ulong type, a compile-time error occurs.

AakashM
  • 62,551
  • 17
  • 151
  • 186
6

All integer literals are of type int, so your variable will be int unless you cast or add an explicit type qualifier at the end:

var quick = 65535;         // int
var brown = (ushort)65535; // ushort
var fox = 65535L;          // long
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523