3

Is there an equivalent method in C# to the Java method Arrays.ToString(byte[])

Found here

Essentially I want to convert a byte array to a string of the format:

"[10, 23, 0, 15]"

The numbers reflecting the value of each byte in the byte array.

Foo Bar User
  • 2,401
  • 3
  • 20
  • 26
William Pownall
  • 760
  • 7
  • 9
  • possible duplicate of [byte\[\] to string in c#](http://stackoverflow.com/questions/1003275/byte-to-string-in-c-sharp) – Blorgbeard Oct 02 '13 at 23:22
  • I don't think that method returns a string in the format that I'm after, using that method I get a string of characters looking something like this "����\0JFIF\0\0`\0`\0\0��\0C\0" – William Pownall Oct 02 '13 at 23:25
  • @BillyPownall What are the input value and output result look like? – Win Oct 02 '13 at 23:29
  • Oh I see, close-vote retracted. Here's the new duplicate: http://stackoverflow.com/questions/8238755/how-to-display-byte-array-hex-values – Blorgbeard Oct 02 '13 at 23:31
  • [This](http://msdn.microsoft.com/en-us/library/3a733s97.aspx) will get you hyphen-separated hex output, if that's ok. – Blorgbeard Oct 02 '13 at 23:32

1 Answers1

3

It's a one-liner. Try this:

static string Array2String<T>( IEnumerable<T> list )
{
  return "[" + string.Join(",",list) + "]";
}

You might need to tweak it a bit for different flavors of T to allow for proper quoting and/or stringification1 etc., but that's the general principle.

1 Not all types have a ToString() that comes back with anything terribly useful since object just hands back the type name.

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135