[ACCEPTED]-How to validate format for string.Format method-string.format

Accepted answer
Score: 23

Let's think about this API, if it exists. The 24 goal is to pre-validate a format string, to 23 make sure String.Format won't throw.

Note that any string 22 which doesn't contain a valid format slot is a 21 valid format string - if you don't try to 20 insert any replacements.

-> So we would 19 need to pass in the number or args we expect 18 to replace

Note that there are tons of different 17 specialty formatting patterns, each with 16 a specific meaning for specific types: http://msdn.microsoft.com/en-us/library/system.string.format.aspx

Although 15 it seems that String.Format won't throw if you pass a 14 format string which doesn't match your argument 13 type, the formatter becomes meaningless 12 in such cases. e.g. String.Format("{0:0000}", "foo")

-> So such an API 11 would be truly useful only if you passed 10 the types of the args, as well.

If we already 9 need to pass in our format string and an 8 array of types (at least), then we are basically 7 at the signature of String.Format, so why not just use 6 that and handle the exception? It would 5 be nice if something like String.TryFormat existed, but 4 to my knowledge it doesn't.

Also, pre-validating 3 via some API, then re-validating in String.Format itself 2 is not ideal perf-wise.

I think the cleanest 1 solution might be to define a wrapper:

public static bool TryFormat(string format, out string result, params Object[] args)
{
   try
   {
      result = String.Format(format, args);
      return true;
   }
   catch(FormatException)
   {
      return false;
   }
}
Score: 0

As long as you're only passing in 1 argument, you 2 can look search custFormat for {0}. If you don't find 1 it, it's invalid.

Score: 0

You can validate with try catch, if format 2 throw exceptin you log information and stop 1 treatment.

try 
{ 
   string.Format(custFormat, params, .., .. , ..);
}
catch(FormatException ex)  
{ 
  throw ex;
}

string message = ProcessMessage(custFormat, name);

More Related questions