3

I'm trying to call string.Join with the following arguments (first param is the separator):

string.Join(";", null, "string", 0); //returns empty string ???.
string.Join(";", null, null, 0); //returns empty string ???.
string.Join(";", null, null, null); //returns ";;;" - Good
string.Join(";", 0, 0, 0); //returns "0;0;0" - Good
string.Join(";", 0, null, 0); // "0;;0" - Good
string.Join(";", null, 0, null); // empty

Can anyone please explain why it acts this way? How to rely on the string.Join in such cases?

2 Answers 2

5

The String.Join(String, Object[]) overload is selected for the following calls:

string.Join(";", null, "string", 0); // empty string
string.Join(";", null, null, 0); // empty string
string.Join(";", 0, 0, 0); // "0;0;0"
string.Join(";", 0, null, 0); // "0;;0"
string.Join(";", null, 0, null); // empty string

From the documentation (see Notes to Callers):

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.

The String.Join(String, String[]) overload, which does not share the same implementation quirk, is selected for this call:

string.Join(";", null, null, null); // ";;;"
Sign up to request clarification or add additional context in comments.

1 Comment

Argh, I checked the wrong overload before asking my question... Anyway, why did they design it so?
2

From the ReferenceSource Join(String separator, params Object[] values)'s implementation

if (values.Length == 0 || values[0] == null)
    return String.Empty;

I think this is your answer.

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.