2

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.

Paul Farry
  • 4,730
  • 2
  • 35
  • 61

1 Answers1

6

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
  • 60,705
  • 7
  • 138
  • 176
  • 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 Apr 09 '10 at 03:00
  • 3
    write an extension method extending BitConverter and let it return new byte[1]{input}. – Femaref Apr 09 '10 at 03:10
  • @Femaref, that's a nice thought. But [it doesn't appear to be possible](http://stackoverflow.com/questions/249222/can-i-add-extension-methods-to-an-existing-static-class) – kdbanman Aug 04 '15 at 21:17