简体   繁体   中英

Strange behavior of string.Join on byte array and startIndex, count

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM