Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add to string if string non empty

Sometime I want to join two strings with a space in between. But if second string is null, I don't want the space.

Consider following code:

void AssertFoo(bool cond, string message = null) {
    ...
    Assert.Fail("Something is foo.{0}", message != null ? " " + message : "");
    ...
}

Is there a more elegant way to do that?

like image 891
THX-1138 Avatar asked Sep 25 '12 17:09

THX-1138


2 Answers

Here is one option that I like. It's better if you already have an IEnumerable<string> with your data, but it's easy enough even if you don't. It also clearly scales well to n strings being joined, not just 1 or two.

string[] myStrings = new string[]{"Hello", "World", null};
string result = string.Join(" ", myStrings.Where(str => !string.IsNullOrEmpty(str)));

Here is another option. It's a bit shorter for this one case, but it's uglier, harder to read, and not as extensible, so I would probably avoid it personally:

//note space added before {0}
Assert.Fail("Something is foo. {0}", message ?? "\b");

In this case we add the space to the format string itself, but if message is null we instead use the backspace character to remove the space that we know is before it in the message.

like image 191
Servy Avatar answered Nov 06 '22 07:11

Servy


For newer versions of C# you can use the following extension method:

public static string Prepend(this string value, string prepend) => prepend + value;

It can be used like this:

Assert.Fail("Something is foo.{0}", message?.Prepend(" "));

Added in 2020:

Today I use this:

public static string Surround(this object value, string prepend, string append = null) => prepend + value + append;
like image 37
AlexDev Avatar answered Nov 06 '22 05:11

AlexDev