I was wondering if there's a syntax for formatting NULL values in string.Format, such as what Excel uses
For example, using Excel I could specify a format value of {0:#,000.00;-#,000.00,NULL}
, which means display the numeric value as number format if positive, number format in parenthesis if negative, or NULL if the value is null
string.Format("${0:#,000.00;(#,000.00);NULL}", someNumericValue);
Edit
I'm looking for formatting NULL
/Nothing
values for all data types, not just numeric ones.
My example is actually incorrect because I mistakenly thought Excel used the 3rd parameter if the value was NULL, but it's actually used when the value is 0. I'm leaving it in there because it's the closest thing I can think of to what I was hoping to do.
I am hoping to avoid the null coalescing operator because I am writing log records, and the data is not usually a string
It would be much easier to write something like
Log(string.Format("Value1 changes from {0:NULL} to {1:NULL}",
new object[] { oldObject.SomeValue, newObject.SomeValue }));
than to write
var old = (oldObject.SomeValue == null ? "null" : oldObject.SomeValue.ToString());
var new = (newObject.SomeValue == null ? "null" : newObject.SomeValue.ToString());
Log(string.Format("Value1 changes from {0} to {1}",
new object[] { old, new }));
question from:
https://stackoverflow.com/questions/7689040/can-i-format-null-values-in-string-format 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…