2

The following test passes as written. Why? (i.e., why does a leading null value in an array cause string.Join() to return empty string?)

[TestMethod]
public void Test_string_Join()
{
    object[] values0 = { "foo", 3, null };
    var text0 = string.Join(", ", values0);
    Console.WriteLine("text0 = " + text0);
    AssertX.AreEqual("foo, 3, ", text0); // works as expected

    object[] values1 = { null, "foo", 3, null };
    var text1 = string.Join(", ", values1);
    Console.WriteLine("text1 = " + text1);
    AssertX.AreEqual("", text1); // does NOT work as expected, why empty?
}

enter image description here

10
  • Because NUL is the signal for end of string in NET and much of Windows Commented Apr 20, 2018 at 2:08
  • Relatd. Commented Apr 20, 2018 at 2:09
  • @Plutonix Nope. A null in the middle of the array doesn't return empty string. Commented Apr 20, 2018 at 2:11
  • 8
    Because the documentation says that. "If separator is null or if any element of values other than the first element is null, an empty string (String.Empty) is used instead. [...] If the first element of values is null, the Join(String, Object[]) method does not concatenate the elements in values but instead returns String.Empty." Commented Apr 20, 2018 at 2:15
  • 1
    @user202729 I was looking at the docs for String.Join(String, String[]). Wow!! String.Join(String, Object[]) and String.Join(String, String[]) are NOT symmetric in this regard!! Commented Apr 20, 2018 at 2:28

1 Answer 1

2

The question is about string.Join() for an "array". It turns out that Microsoft is violating the principle of least astonishment and String.Join(String, **Object[]**) behaves differently from String.Join(String, **String**[]) wrt a leading null. The object[] overload has the issue; the string overload behaves as one would expect.

I believe Microsoft is confessing as much when they refer to the "issue" and provide a "workaround" in the object[] overload documentation (link provided by @user202729).

I did not expect the docs for object[] overload to be different than the string[] overload (which I read thoroughly).

Sign up to request clarification or add additional context in comments.

Comments

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.