I’ve been trying to re-create BitConverter.GetBytes. However, every value type should be allowed to be passed. The method should then detect its type (Int32, Int16, Byte etc.) and dynamically call the corresponding BitConverter.GetBytes method. My try is to use reflection.
This is what my code looks like:
public static class BitConverterExtensions
{
public static byte[] GetBytes(ValueType obj)
{
Type tObj = obj.GetType();
Type tBitConverter = typeof(BitConverter);
Type tSelf = typeof(BitConverterExtensions);
MethodInfo miGetBytes = tBitConverter.GetMethod("GetBytes", new Type[] { tObj });
byte[] result = (byte[])miGetBytes.Invoke(null, new object[] { obj });
return result;
}
}
It works just fine if I pass ints, longs, floats, doubles, bools etc.
The only thing that does not work is passing a byte. If a byte is passed, an AmbiguousMatchException is thrown. However, I cannot see any method with the same signature as
byte[] GetBytes(byte)
What am I doing wrong and why is it only not working if a byte is passed?
That’s how I’m calling the method:
byte[] result = BitConverterExtensions.GetBytes((byte)123);
The problem is that there is no overload of
BitConverter.GetBytes()that accepts abyte. It recognizes this so attempts to promote thebyteto one that can be used. However there are many different candidates that could be promoted to thus the ambiguity error. You might have to special case for that type to just throw the argument into a separate byte array yourself.