Question

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)?

Was it helpful?

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.

OTHER TIPS

I think you are worrying too much about this. If the format string is invalid, let string.Format throw the exception for you. If you do not want a FormatException to be thrown, catch it and throw the exception you want.

It should also not really be a problem that you have already done some some processing (eg. evaluating lambda conversions) because this is after all an exceptional circumstance (with possibly the exception that the lambdas are very costly, in which case do the string.Format test first without processing the arguments to check it is valid and then repeat it when you need to later after the processing).

Use a regex to count the number of templates, but be careful, because

string.Format("{0}{0}", 123)

is valid.

You really need to provide more info for this question to be answered ok...

You could do a RegEx for the brace formatters and then compare them to the length of the value array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top