Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which int type does var default to? [duplicate]

Tags:

c#

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.

like image 744
PiousVenom Avatar asked Oct 19 '12 14:10

PiousVenom


2 Answers

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.

like image 55
AakashM Avatar answered Oct 20 '22 23:10

AakashM


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
like image 44
Sergey Kalinichenko Avatar answered Oct 21 '22 01:10

Sergey Kalinichenko