Search code examples
c#overloadingparams-keyword

C# function with variable number of arguments causes confusion when multiple overloads available


    public string GetErrorMessage(params object[] args)
    {
        return GetErrorMessage("{0} must be less than {1}", args);
    }

    public string GetErrorMessage(string message, params object[] args)
    {
        return String.Format(message, args);
    }

Here is the call

    Console.WriteLine(GetErrorMessage("Ticket Count", 5));

Output

Ticket Count

This means, it invokes the 2nd overload of the method with 2 parameters: message, variable number of object arguments.

Is there a way to force it to invoke first overload rather than second?


Solution

  • The problem you are seeing is caused because the first item in your method call is a string and therefore will alway match the second method call. You can do 1 of the following to get around the problem:

    If the order of the args is not important you could simply make sure that the first item is not a string:

    this.GetErrorMessage(5, "Ticket Count");
    

    Or you can cast the string to an object:

    this.GetErrorMessage((object)"Ticket Count", 5);
    

    You could always make this call however it does break the whole purpose of using params:

    this.GetErrorMessage(new object[] {"Ticket Count", 5 });