Search code examples
c#testingformattingparams-keyword

How can I tell the number of replacements in a formatter string?


Given the following method: (real method has a few more parameters, but the important ones are below...)

public string DoSomething(string formatter, params string[] values)
{
    // Do something eventually involving a call to String.Format(formatter, values);
}

Is there a way to tell if my values array has enough objects in it to cover the formatter, so that I can throw an exception if there aren't (short of doing the string.Format; that isn't an option until the end due to some lambda conversions)?


Solution

  • I'm still not clear why you think you cannot use string.Format to test it. If the passed in formatter is supposed to have placeholders for the items in values, then you should be able to do this:

    static void TestFormat(string formatter, params string[] values)
    {
        try
        {
            string.Format(formatter, values);
        }
        catch (FormatException e)
        {
            throw new Exception("the format is bad!!", e);
        }
    }
    

    Sample Usage:

            TestFormat("{0}{1}{2}", "a", "b", "c"); // works ok
            TestFormat("{0}{1}{2}", "a", "b"); // throws exception
            TestFormat("{0}{1}{2}}0{", "a", "b", "c"); // throws exception
    

    Trying to do this with a regular expression is going to be tough, because what about something like this:

    "{0}, {1}, {abc}, {1a4} {5} }{"
    

    {abc} and {1a4} aren't valid for string.Format, and you also have to determine for each valid number ({0}, {1}, {5}) that you have at least that many arguments. Also, the }{ will cause string.Format to fail as well.

    I just used the former approach described above in a recent project and it worked great.