I wrote my own class which converts C# standard primitives into byte arrays.
Later on, I took a look at the BitConverter
class source, to see how pros did it.
My code example:
public static byte[] getBytes(short value) {
byte[] bytes = new byte[2];
bytes[0] = (byte)(value >> 8);
bytes[1] = (byte)value;
return bytes;
}
BitConverter class code:
public unsafe static byte[] GetBytes(short value)
{
byte[] bytes = new byte[2];
fixed(byte* b = bytes)
*((short*)b) = value;
return bytes;
}
Why are their functions tagged as unsafe and use fixed operator?
Are such functions error prone even if they use unsafe? Should I just drop mine and use their implementation? Which is more efficient?
Yes, drop yours and use the standard library.
It is more efficient, because it copies both bytes at once by casting the byte array to a short pointer. To do this it requires fixed to allow the use of pointers, and hence the unsafe keyword.
Unsafe code is generally to be avoided in your own assemblies, as it means your code cannot be guaranteed safe, and so can only be run in fully trusted environments.
However, since Bitconverter is part of the standard .Net assemblies that are signed by Microsoft, Windows knows they are ok.
Library functions are less error prone too, because they have been battle hardened by millions of developers using them every day, whereas your function has been tested only by you.