[C#] I wish I knew : BitConverter

I’ve been a professional C# developer for years now, but I’m still discovering trivial stuffs. In “I wish I knew”, I describe a feature that I missed.

In my programmer’s life, I encountered a lot of situations where I needed to log the content of a buffer. In that case, I want to convert a byte[] into a string containing the hexadecimal representation of each byte.

Implementation 1 : StringBuilder

In 2005, as a rookie C# developer, I used to write something like that:

static string ConvertBufferToString(byte[] buffer)
{
    var sb = new StringBuilder();
    foreach (var value in buffer)
    {
        sb.AppendFormat("{0:X2}-", value);
    }
    sb.Length--;
    return sb.ToString();
}

Then when I call:

byte[] buffer = { 0xDE, 0xAD, 0xBE, 0xEF };
Console.WriteLine(ConvertBufferToString(buffer));

It displays DE-AD-BE-EF as expected.

Implementation 2 : LINQ

Then, in 2008, when LINQ came out, I changed to something like:

static string ConvertBufferToString(byte[] buffer)
{
    return string.Join("-", buffer.Select(x => x.ToString("X2")));
}

This is much better than implementation number one.

Implementation 3 : BitConverter

I was satisfied with the LINQ approach until a recent discovery: BitConverter.ToString(byte[]) already does that !

static string ConvertBufferToString(byte[] buffer)
{
    return BitConverter.ToString(buffer);
}

You know what ? This method has been available since .NET Framework 2, which mean I could use it from the beginning !

DAMN IT !