tags:

views:

236

answers:

6

I just notice if i pass a value such as 1 in a function parameter it will work if it excepts int, long and i assume the others. However if i do int i = value, it doesnt. I was wondering, what type is it?

A: 

As I understand it, the compiler will use type-hinting to determine the type of the literal at compile time.

Nick
A: 

The type is determined.

If you have this function:

public void SomeFunc( long i );

and you call it like this:

SomeFunc (1);

Then C# will see this '1' as being a long.

Frederik Gheysels
+4  A: 
(1).GetType().ToString() //is System.Int32
Kobi
For completeness, the original poster may want examples for 'L', 'U' and 'UL' as well maybe? :)
jerryjvl
+3  A: 

You can suffix literal integers to make the type explicit, otherwise the value will be implicitly interpreted as though it were the target type (assuming it doesn't overflow the target).

var myLong = 123L;
var myInt = 123;
var myByte = (byte)123; // i'm not aware of a suffix for this one

// unsigned variants
var myULong = 123UL;
var myUInt = 123U;
Drew Noakes
Regarding the byte suffix your "un-awareness" is well founded; there is none ;o)
Fredrik Mörk
+3  A: 

Take a look at the integer literals specification:

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.
hmemcpy
Love your avatar (or rather; the sound it represents). Good answer too :o)
Fredrik Mörk
Porcupine Tree are awesome :)
hmemcpy
A: 

Integer literals are int per default, but since there's an implicit conversion from int to long, you can still call a method which take a long with an int.

Brian Rasmussen