C# Language Overload Resolution "params" is not expanded, unless necessary.

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

The following program:

class Program
{
    static void Method(params Object[] objects)
    {
        System.Console.WriteLine(objects.Length);
    }   
    static void Method(Object a, Object b)
    {
        System.Console.WriteLine("two");
    }
    static void Main(string[] args)
    {
        object[] objectArray = new object[5];

        Method(objectArray);
        Method(objectArray, objectArray);
        Method(objectArray, objectArray, objectArray);
    }
}

will print:

5
two
3

The call expression Method(objectArray) could be interpreted in two ways: a single Object argument that happens to be an array (so the program would output 1 because that would be the number of arguments, or as an array of arguments, given in the normal form, as though the method Method did not have the keyword params. In these situations, the normal, non-expanded form always takes precedence. So, the program outputs 5.

In the second expression, Method(objectArray, objectArray), both the expanded form of the first method and the traditional second method are applicable. In this case also, non-expanded forms take precedence, so the program prints two.

In the third expression, Method(objectArray, objectArray, objectArray), the only option is to use the expanded form of the first method, and so the program prints 3.



Got any C# Language Question?