0

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")
6
  • What's the type of x? (If it's an int, it can't be null...) Commented Mar 19, 2013 at 19:04
  • 1
    And why are you using string.Format when the result is just the True or False string? You really need a more complete example before we can help you much... Commented Mar 19, 2013 at 19:05
  • hey Jon... I am rendering my title on my grid column. Therefore I need to format the title with my json data Commented Mar 19, 2013 at 19:07
  • That doesn't explain why you'd use string.Format with just a format string of {0}. Nor does it tell us the type of x. Again, a better example is required. Commented Mar 19, 2013 at 19:16
  • guys... all I wanted to know was how to add another else statement in the string.format? Thanks to Alex. Now I have already got it working... Thanks for your concern though Jon :) Commented Mar 19, 2013 at 19:19

3 Answers 3

4
String.Format("{0}", x == null ? "<null>": (x == 0 ? "True" : "False"))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Alex... this is all I needed to know(format) without all the extras... thanks for the quick response
2

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.

2 Comments

with more then 2-3 values it is far more readable then ternary if. Try adding another case to ternary if and see what's cleaner. Actually, don't add another, just express these 4 cases with it.
Thank you for this answer as well Zdeslav, but for my simple purpose, I am accepting Alex's answer
2

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"))

2 Comments

I wouldn't say it's always a bad idea. I've seen it put to very good effect - but I wouldn't do it within the method call here...
I already put 'almost' in front of that. My alternative isn't that great either, but that's also from the confusion about the type of x.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.