How do you check a composite format string in C # against its types of target arguments?

Given the user-supplied composite formatted string (for use with String.Format ) and the set of types representing the arguments that will be used to format the composite format string, how can you verify that the value provided by the user is valid?

Simply create a regular expression to verify that the general syntax of the argument placeholders matches " {index[,alignment][:formatString]} " for the documentation . And it’s not too difficult to verify that the placeholder indices in a compound format string are less than the actual number of typed arguments (i.e., they do not reference an argument that will not be specified). However, given the types for the arguments to be passed in, are also known, you can also verify that " :formatString " is suitable for these types.

For example, you want to verify that the user does not specify " {0:dddd MMMM} " as a format string when the first argument type (index 0) is a number ( String.Format("{0:dddd MMMM}", 1234) gives " dddd MMMM "). The number of options " :formatString " by type is too large to manually check everything. Is there any other way? Or do you just need to live with a user who may indicate the wrong format string?

Suppose there is no custom IFormatProvider , ICustomFormatter or IFormattable in the game here. Just the basic types are already in the .NET Framework. Bonus points for accessing custom content.

+4
source share
3 answers

There is no built-in way to do this, AFAIK.

You can code each common case manually, but I do not recommend it.

( edit ). One pragmatic parameter might be try/catch - check the format as early as possible when the user enters it.

+5
source

Sorry, but the way to do this is:

 try { string.Format(godKnowsWhat, aBunchOfArguments); } catch(FormatException) { // use exception for control flow lol } 

Yes, it seems to be bad.

+4
source

If an incorrect format string specified by the user can throw an exception, maybe you can just try it? Yes, this is a naive and trivial idea.

+1
source

All Articles