How would I do if statement in string.format? I need to check if x=0, x=1 or x=null I know I can do with two values but I am not sure how to add another else statment here
String.Format("{0}", x == 0 ? "True" : "False")
String.Format("{0}", x == null ? "<null>": (x == 0 ? "True" : "False"))
I don't like nesting of ternary ifs. In general case and depending on version of C# you use, you can try this:
var values = new Dictionary<int?, string>()
{
{ 0, "zero"},
{ 1, "one"},
{ 2, "two"},
{ null, "none"}
};
String.Format("{0}", values[x]);
IMO, tables always beat complex if statements for more than 3 values.
how to add another else statment here
Nesting of ?: is possible but almost always a bad idea.
A direct answer, assuming x is int? is to just use ( ) :
String.Format("{0}", x == null ? "Null" : (x.Value == 0 ? "True" : "False"))
x? (If it's anint, it can't be null...)string.Formatwhen the result is just theTrueorFalsestring? You really need a more complete example before we can help you much...string.Formatwith just a format string of{0}. Nor does it tell us the type ofx. Again, a better example is required.