0

Let's say that I have a method with 2 signatures:

void Foo(int a);
void Foo(long a, string s = null);

If I invoke Foo like this:

Foo(1);

It seems to call the first one of the two. Is it because numbers passed directly as an argument are treated as int32 by default? Where is this specified?

Johan
  • 35,120
  • 54
  • 178
  • 293

2 Answers2

6

Section 2.4.4.2 (Integer literals) of the C# 5.0 specs states:

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.

So the first bullet applies to your case, as you have no suffix, and 1 fits into the first item in the list, int, so the integer literal 1 is of type int.

Servy
  • 202,030
  • 26
  • 332
  • 449
3

The literal value 1 alone is by default an int (Int32). If you want to explicitly call the version that takes a long, make sure you are passing a long value, for example:

Foo(1L);

Servey's answer does a superb job of explaining the why.

Community
  • 1
  • 1
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194