views:

93

answers:

3

Per the documentation, String.Format will throw a FormatException if either (A) the format string is invalid or (B) the format string contains an index that cannot be found in the args array.

I want to be able to determine which (if either) of those conditions fail on any arbitrary string and array of arguments.

Is there anything that can do that for me? Thanks!

+1  A: 

The FormatException message property is set to a distinct message in each of those cases.

gbogumil
I did not realize this, thanks.
Tinister
A: 

And you don't want to do...?

works = true;
try {
  String.Parse(Format, ObjectArray);
} catch FormatException {
works = false; }
qor72
No, this doesn't tell me which condition failed.
Tinister
+1  A: 

Follow up to gbogumil's answer, in the first case you get:

"Input string was not in a correct format."

and in the second, you get:

"Index (zero based) must be greater than or equal to 
zero and less than the size of the argument list."

If you need to sense which (for user messaging or logging), then you could use a try catch like qor72 suggested, and check for what the error message starts with. In addition, if you need to capture what the format string was, and what the args were, you will need to do something like this:

        string myStr = "{0}{1}{2}";
        string[] strArgs = new string[]{"this", "that"};
        string result = null;

        try { result = string.Format(myStr, strArgs); }

        catch (FormatException fex)
        {
            if (fex.Message.StartsWith("Input"))
                Console.WriteLine
                  ("Trouble with format string: \"" + myStr + "\"");
            else
                Console.WriteLine
                  ("Trouble with format args: " + string.Join(";", strArgs));
            string regex = @"\{\d+\}";
            Regex reg = new Regex(regex, RegexOptions.Multiline);
            MatchCollection matches = reg.Matches(myStr);
            Console.WriteLine
                ("Your format has {0} tokens and {1} arguments", 
                 matches.Count, strArgs.Length );

        }

EDIT: Added the simple regex to count format tokens. Might help...

Hope this helps. Good luck!

Audie
Thanks for your effort. Using exception handling for control flow is not ideal but at least I can inspect the message on the exception object.
Tinister
Your regex will not work, however, since it doesn't take into account escaping braces or using alignment (e.g. `{0,5}`) or a format component (e.g. `{0:d}`). I tried going down that path too, but found that these format strings are actually pretty complicated. I was hoping something would expose this complication instead of me redoing everything, but oh well.
Tinister
Yes, my regex was for the simplest case, and I completely agree with you on exceptions and control flow. It is unfortunate that the .net framework so often forces you to use exceptions.
Audie