Add to row if row is not empty

Someday I want to join two lines with a gap between them. But if the second line is null, I do not want this space.

Consider the 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 this?

+8
c # string-formatting
source share
5 answers

Here is one of the options 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 scales well to n lines that are concatenated, 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. This is a little shorter for this one case, but it is uglier, harder to read, and not as extensible, so I will probably personally avoid it:

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

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

+24
source share
 Assert.Fail("Something is foo.{0}", (" " + message).TrimEnd()); 

Of course, this will lead to the creation of several string objects, but it is unlikely that such problems with micro-optimization will matter in the vast majority of programs. It can be considered an advantage of this method that it processes not only the zero message, but also the message of all spaces.

+1
source share

Try the following:

 string joinedString = string.IsNullOrEmpty(message2) ? message1 : message1 + " " + message2; 
0
source share

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 as follows:

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

The most elegant way is to use the built-in keyword of the String class.

 String.IsNullOrEmpty 

This way you will not have a problem.

-5
source share

All Articles