tags:

views:

56

answers:

1

Given the following information

Public Enum Request As Byte
    None = 0
    Identity = 1
    License = 2
End Enum

Protected mType As Communication.Request

mType = Communication.Request.Identity

Debug.Print (BitConverter.GetBytes(mType).Length.tostring)

2

Why does bitconverter report that mType is a length of 2. I would have thought that passing a Byte into BitConverter.GetBytes would just return the Byte.

I mean it's no big deal because it's only sending a very small block of data across a TCP Socket, but I'm just intrigued why it thinks it's 2 bytes.

+2  A: 

Because there is no overload for BitConverter.GetBytes(Byte b) (see msdn), the nearest available implicit overload is used, which in this case, returns a byte[2].

Using simple code:

        byte b = 1;
        BitConverter.GetBytes(b);

Compiling this and using ildasm, we see that the method for an int16 (which is a short) is called:

.method public hidebysig instance void  bytetest() cil managed
{
  // Code size       11 (0xb)
  .maxstack  1
  .locals init ([0] uint8 b)
  IL_0000:  nop
  IL_0001:  ldc.i4.1
  IL_0002:  stloc.0
  IL_0003:  ldloc.0
  IL_0004:  call       uint8[] [mscorlib]System.BitConverter::GetBytes(int16)
  IL_0009:  pop
  IL_000a:  ret
} // end of method Test::bytetest

This is also visible while hovering the method in Visual Studio (the selected overload gets shown in the tooltip)

Femaref
thats a bugger because i wanted to make it dynamic calculating my sizes using bitconverter... guess i'll need to do it manually when my enums are Byte
Paul Farry
write an extension method extending BitConverter and let it returnnew byte[1]{input}.
Femaref