5

Almost daily I come across code of the following form:

string x = "foo" + (someTest ? "bar" : "");

Surely there must be a nicer way to succinctly append a string only if some value is true?

This:

string x = "foo";
if (someTest)
    x += "bar";

does not satisfy my appetite, because I often want to use the string directly (e.g. as a function argument), without storing it in a variable.

3
  • 2
    how come you're so sure there is a nicer way? Commented May 15, 2012 at 9:20
  • I'm not, it's just wishful thinking. Commented May 15, 2012 at 9:20
  • @Botz: without wasting performance and or memory, whilst behaviorally equivalent. Commented May 15, 2012 at 9:32

5 Answers 5

9

What about an Extension Method?

string x = "foo".AppendIf(someTest, "bar");


public static string AppendIf(this string value, bool expression, string append)
{
    return expression
       ? value + append;
       : value;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Indeed, but using expression before the string in the methods reads more natural then "foo".AppendIf("bar", someTest); +1
agreed, like the ternary operator.
6

Why not write your own extension method to do this?

public static string AppendIf(this string value, string toAppend, bool condition)
{
    return condition ? String.Format("{0}{1}", value, toAppend) : value;
}

Comments

4

use extensions

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

1 Comment

I wish this "great mind" would leave, so I could say: "look at that esskar go!"
1

Assuming that the string literals could also be variables:

if there is I have yet to find one.

I think the two examples you have are the best.

The only objection is that if you need to conditionally add many strings using the second solution with a stringbuilder instead of concatenation should be a better solution considering performance, readability and maintainability.

Deep nested ? : constructs can be very hard to follow, especially if there are multiple forks.

1 Comment

esskars solution is a nice way to make the code more readable.
0

How about just:

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

1 Comment

Aargh, the redundancy! I appreciate how it ditches the concatenation altogether, but the redundancy sticks out like a sore thumb.

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.