A couple of month ago I wrote a simple program in Java.
I have two overloaded methods called F and one of them takes variable length argument.
This program will not compile, because calling F(4) in main method is ambiguous and the
compiler does not know which method to choose.
class Example
{
static void F(int... array)
{
Console.WriteLine("We are in first method");
}
static void F(int x, int ... array)
{
Console.WriteLine("We are in second method");
}
static void main()
{
F(4);
}
}
I wrote an equivalent program in C# as below and I was expecting a compile-error.
Surprisingly the program compiled successfully without any error.
The output of the program is “We are in second method” which means that the second
overloaded method was chosen !!!
Isn’t this strange ?? Both F methods can be a candidate for calling, but why CLR chooses the second overloaded method ???
class Example
{
static void F(params int[] array)
{
Console.WriteLine("We are in first method");
}
static void F(int x, params int[] array)
{
Console.WriteLine("We are in second method");
}
static void Main()
{
F(4);
}
}
C# takes that approach because it says so in the C# language specification:
EDIT: Had the wrong section highlighted. Fixed now.