5

I'm using string.Join to be able to show what values an array contains. I have stumbled upon a strange behavior when using a byte array and startIndex and count.

byte[] byteArr = new byte[]{1,2,3,4,5,6,7,8};
string[] stringArr = new string[] {"1","2","3","4","5","6","7","8"};

Console.WriteLine(string.Format("Whole byteArr: {0}",string.Join(", ", byteArr)));
Console.WriteLine(string.Format("Whole stringArr: {0}",string.Join(", ", stringArr)));

Console.WriteLine(string.Format("0 - 5 byteArr: {0}",string.Join(", ", byteArr,0,5)));
Console.WriteLine(string.Format("0 - 5 stringArr: {0}",string.Join(", ", stringArr,0,5)));

gives this result

Whole byteArr: 1, 2, 3, 4, 5, 6, 7, 8

Whole stringArr: 1, 2, 3, 4, 5, 6, 7, 8

0 - 5 byteArr: System.Byte[], 0, 5

0 - 5 stringArr: 1, 2, 3, 4, 5

Why do string.Join(", ",byteArr,0,5) return the string System.Byte[], 0, 5

1 Answer 1

6

Currently, you're calling this overload of the Join method which concatenates the elements of an object array, using the specified separator between each element.

public static string Join(
    string separator,
    params object[] values
)

not this:

public static string Join(
    string separator,
    string[] value,
    int startIndex,
    int count
)

Which concatenates the specified elements of a string array, using the specified separator between each element.

This is simply because the overload that takes a startIndex and count is only called if you supply a string array as the second argument to the Join method.

Because you're supplying an array that is not a string as the second argument to the Join method, it ends up called the first overload I've shown above and hence you're seeing System.Byte[], 0, 5 because calling ToString on a byte array will yield a System.Byte[], the ToString representation of 0 is 0 , 5 is 5 and therefore the result is System.Byte[], 0, 5.

So how do we make sure that we call the version that accepts a startIndex and count?

If you wish to call this overload of the Join method, and the array you have is not a string[] then transform the elements of the array you have to a string array, example:

Console.WriteLine(string.Format("0 - 5 byteArr: {0}", 
     string.Join(", ", byteArr.Select(b => b.ToString()).ToArray(), 0, 5)));

By performing byteArr.Select(b => b.ToString()).ToArray() we make sure that we're caling the overload with the startIndex and count parameters.

1
  • Aha! I really need to read the documentation more carefully! Thanks for pointing out my error and also providing a solution!
    – Andis59
    May 13, 2018 at 11:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.