Why is string.Join (string, object []) special?

I looked at the following expressions:

string.Join(",", new object[] { null, "StackOverflow" }) string.Join(",", new string[] { null, "StackOverflow" }) string.Join(",", new object[] { string.Empty, "StackOverflow" }) string.Join(",", new string[] { string.Empty, "StackOverflow" }) 

I would think that they will return the same value:

 ,StackOverflow 

However, the first expression actually returns string.Empty . This is actually the behavior defined :

If the first element of values ​​is null, the Join (String, Object []) method does not combine the elements in the values, but returns String.Empty. A number of workarounds are available for this problem. The easiest way is to assign a String.Empty value to the first element of the array, as shown in the following example.

Does anyone know the reason for this inconsistency?

+7
string
source share
1 answer

In your favorite decompiler you can see the code for the method

 public static string Join(string separator, params object[] values) { if (values == null) throw new ArgumentNullException("values"); if (values.Length == 0 || values[0] == null) return string.Empty; if (separator == null) separator = string.Empty; StringBuilder sb = StringBuilderCache.Acquire(16); string str1 = values[0].ToString(); if (str1 != null) sb.Append(str1); for (int index = 1; index < values.Length; ++index) { sb.Append(separator); if (values[index] != null) { string str2 = values[index].ToString(); if (str2 != null) sb.Append(str2); } } return StringBuilderCache.GetStringAndRelease(sb); } 

The part responsible for the special behavior

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

but we can see a few lines below

  string str1 = values[0].ToString(); if (str1 != null) sb.Append(str1); 

It seems rather strange to me to return to values[0] == null , but to process values[0].ToString() == null . Combined with the wording in MSDN (β€œproblem”, β€œworkaround”), the fact that this overload is relatively new (.NET 4.0), and the fact that other Join have a different implementation that accept null as the first element, it looks like an error to me and is not really the intended exception.

Of course, this is only my interpretation, not the final answer ...

+3
source share

All Articles