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

    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 challenge

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

Output

Ticket Count

This means that it causes a second method overload with two parameters: a message, a variable number of object arguments.

Is there a way to make it cause the first overload, not the second?

+4
source share
3 answers

The problem you see is caused by the fact that the first element in the method call is stringand therefore will always correspond to the call to the second method. You can do one of the following to solve the problem:

, , string:

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

string object:

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

, params:

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

, params . , - . , - object []. - :

Console.WriteLine(GetErrorMessage(new object[] { "Ticket Count", 5 }));
+2

All Articles