A cleaner solution than adding an empty string with a conditional statement

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.

+3
source share
5 answers

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;
}
+8
source

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;
}
+5
source

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");
+3

, :

, .

, .

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.

+1
source

How about just:

string x = someTest ? "foobar" : "foo";
0
source

All Articles