I would like to do some condition formatting of strings. I know that you can do some conditional formatting of integers and floats as follows:
Int32 i = 0;
While not addressing the OP directly, this does fall under the question title as well.
I frequently need to format strings with some custom unit, but in cases where I don't have data, I don't want to output anything at all. I use this with various nullable types:
///
/// Like String.Format, but if any parameter is null, the nullOutput string is returned.
///
public static string StringFormatNull(string format, string nullOutput, params object[] args)
{
return args.Any(o => o == null) ? nullOutput : String.Format(format, args);
}
For example, if I am formatting temperatures like "20°C", but encounter a null value, it will print an alternate string instead of "°C".
double? temp1 = 20.0;
double? temp2 = null;
string out1 = StringFormatNull("{0}°C", "N/A", temp1); // "20°C"
string out2 = StringFormatNull("{0}°C", "N/A", temp2); // "N/A"