Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using String.Format is there a simple way to add parenthesis around a string value if it is not null or empty

I am attempting to isolate (for localization purposes) the formatting of some messages. In one of the cases, I have several parameters, some of which may be an empty string. An example is probably called for here....

If the parameters are Parameter one and Parameter two then I want the result to be Some message Parameter one (Parameter two).

If the parameters are Parameter one and string.Empty then I want the result to be Some message Parameter one

If Parameter two was a numeric value, then I could use something like:

String.Format("Test {0}{1:' ('#')'}", "Parameter one", 12);

This operates as I'd expect - specifically if the second parameter is null the output is just Test Parameter one.

Unfortunately I haven't (yet) found a similar option which works with string parameters. Is there one?

Clarification: I am fully aware of numerous ways to get the result I need in code. I specifically want to know if there is a similar built-in mechanism for strings to the numeric one shown above.

like image 399
Richard J Foster Avatar asked Jul 01 '10 12:07

Richard J Foster


1 Answers

You could always attempt writing your own custom string formatter by implementing IFormatProvider and ICustomFormatter

Then invoke it as

var stringValue = string.Format(new NewCustomStringFormatInfo(),
     "Test {0}{1:' ('#')'}", "Parameter one", 12)
like image 177
Chris Marisic Avatar answered Oct 11 '22 02:10

Chris Marisic