In my program I have a PacketFactory
that builds buffers ready for sending over a NetworkStream
. As you can see below this method takes a short as parameter. This short is passed to BitConverter.GetBytes
.
internal static class PacketFactory
{
internal static byte[] ToBuffer(PacketType type, short value)
{
byte[] packet = PacketTypeFactory.ToBuffer(type);
byte[] valueBytes = BitConverter.GetBytes(value);
byte[] buffer = new byte[packet.Length + valueBytes.Length];
Array.Copy(packet, 0, buffer, 0, packet.Length);
Array.Copy(valueBytes, 0, buffer, packet.Length, valueBytes.Length);
return buffer;
}
}
Now my problem: BitConverter.GetBytes
has 10 overloads. I want to easily use all this overloads for my value
parameter in the ToBuffer
method.
Naive solution: Create all overloads that also exist on BitConverter.GetBytes
and pass everything to an internal method. Is there a better way of solving this?
internal static class PacketFactory
{
private static byte[] ToBuffer(PacketType type, byte[] value)
{
byte[] packet = PacketTypeFactory.ToBuffer(type);
byte[] buffer = new byte[packet.Length + value.Length];
Array.Copy(packet, 0, buffer, 0, packet.Length);
Array.Copy(value, 0, buffer, packet.Length, value.Length);
return buffer;
}
internal static byte[] ToBuffer(PacketType type, short value)
{
return ToBuffer(type, BitConverter.GetBytes(value));
}
internal static byte[] ToBuffer(PacketType type, int value)
{
return ToBuffer(type, BitConverter.GetBytes(value));
}
}