Almost daily, I find code like this:
string x = "foo" + (someTest ? "bar" : "");
Of course, should there be a more convenient way to succinctly add a line only if some value is true?
It:
string x = "foo"; if (someTest) x += "bar";
does not satisfy my appetite, because I often want to use a string directly (for example, as an argument to a function) without storing it in a variable.
What about the extension method?
string x = "foo".AppendIf(someTest, "bar"); public static string AppendIf(this string value, bool expression, string append) { return expression ? value + append; : value; }
Why not write your own extension method for this?
public static string AppendIf(this string value, string toAppend, bool condition) { return condition ? String.Format("{0}{1}", value, toAppend) : value; }
public static class StringExtensions { public static string AppendIf(this string s, bool condition, string append) { return condition ? s + append : s; } } string x = "Foo"; x.AppendIf(someTest, "bar"); // or even string y = "Foo".AppendIf(someTest, "bar");
, :
, .
The only objection is that if you need to conditionally add many lines using the second solution using stringbuilder instead of concatenation, this should be the best solution, taking into account performance, readability and maintainability.
Deeply nested ?: designs can be very difficult to follow, especially if there are several forks.
How about just:
string x = someTest ? "foobar" : "foo";