How can I tell if a .Net format string is valid?

Viewed 81

.Net includes a wide range of built in formatters to control the output when converting an object to a string e.g. ToString("N2"). How can I test if a given format string is actually valid?

If I pass a garbage formatter ToString(...) then the output seems to be the literal of that formatter. For example (in my en locale):

10.ToString("F");    // Outputs '10.00'
10.ToString("typo"); // Outputs 'typo'

I am trying to catch the case where a format has been overridden in one of our translations (perhaps by a non-developer), and the format has been accidentally typo'd.

It seems strange that an invalid formatter is allowed through without exception, and even more strange that when this case does occur, the invalid formatter is used as the output instead of falling back to the source object.

1 Answers

Note sure if this is really the best approach, however using types that implement IFormattable:

Note : that this is likely to give you false positives and unexpected behaviour in certain formats. The only other option is to create a white list (which would in any implementation be equally flawed)

public static bool TryFormat<T>(this T target, string format, out string result)
   where T : IFormattable
{
   result = null;
   try
   {
      return (result = target.ToString(format,null)) != format;
   }
   catch 
   {
      return false;
   }
}

Usage

if(!10.TryFormat("Typo", out var test))
   Console.WriteLine("yeah nah");
Related