Shimmy Weitzhandler
Shimmy Weitzhandler

Reputation: 104692

string.Join odd behavior

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?

Upvotes: 3

Views: 230

Answers (2)

Anders Chen
Anders Chen

Reputation: 81

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.

Upvotes: 2

Robby Cornelissen
Robby Cornelissen

Reputation: 97120

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

Upvotes: 5

Related Questions