c# switch on variable type

Is there a cuter way to do this? Given a byte stream to convert it to the desired number type.

(Assume the calling code will be handling data types relevant to the number of bytes in the stream).

    public void GetValue(byte[] bytes, ref UInt16 value)
    {
        if (BitConverter.IsLittleEndian)
            Array.Reverse(bytes);
        value = BitConverter.ToUInt16(bytes, 0);
    }
    public void GetValue(byte[] bytes, ref UInt32 value)
    {
        if (BitConverter.IsLittleEndian)
            Array.Reverse(bytes);
        value = BitConverter.ToUInt32(bytes, 0);
    }
    public void GetValue(byte[] bytes, ref UInt64 value)
    {
        if (BitConverter.IsLittleEndian)
            Array.Reverse(bytes);
        value = BitConverter.ToUInt64(bytes, 0);
    }
    etc...

I imagine there's a better way, by switching on the type of value, for instance, rather than having replicated overloads.

Jon Skeet
people
quotationmark

Well you can extract the conditionality of the array reversal, and I wouldn't use overloads at all:

public ushort GetUInt16(byte[] bytes)
{
    ReverseIfLittleEndian(bytes);
    return BitConverter.ToUInt16(bytes, 0);
}

public uint GetUInt32(byte[] bytes)
{
    ReverseIfLittleEndian(bytes);
    return BitConverter.ToUInt32(bytes, 0);
}

public ulong GetUInt64(byte[] bytes)
{
    ReverseIfLittleEndian(bytes);
    return BitConverter.ToUInt64(bytes, 0);
}

private static void ReverseIfLittleEndian(byte[] bytes)
{
    if (BitConverter.IsLittleEndian)
    {
        Array.Reverse(bytes);
    }
}

If you're really aiming to have a single method, I would avoid trying to get "cute" and stick with "simple and readable". Yes, you end up with several similar methods - but each is simple to understand, simple to call, and basically zero maintenance. Sounds good to me...

people

See more on this question at Stackoverflow