A common give-away that a piece of code was written by a developer new to the .NET framework, is the re-inventing of the simple things - like writing their own function for creating a string of comma separated values instead of using String.Join. Considering the vast number of classes available in the BCL, writing such code is quite understandable. Having worked with the framework for about 7 years though, I still from time to time catch myself writing some utility method that I later find out is already in the framework. Just the other day, for instance, I needed to convert an integer to a byte array and vice versa, which yielded the following functions:
public static byte[] GetBytes(int number)
{
byte[] dword = new byte[4];
dword[0] = (byte) (number & 0x00FF);
dword[1] = (byte) ((number >> 8) & 0x000000FF);
dword[2] = (byte) ((number >> 16) & 0x000000FF);
dword[3] = (byte) ((number >> 24) & 0x000000FF);
return dword;
}
public static int ToInt32(byte[] bytes)
{
int number = (int)bytes[0];
number |= (int)bytes[1] >> 8;
number |= (int)bytes[2] >> 16;
number |= (int)bytes[3] >> 25;
return number;
}
Shortly after, I came across System.BitConverter, which already has methods to do just that (aswell as for conversions of other primitives):
BitConverter.GetBytes(number);
BitConverter.ToInt32(bytes, 0);
Incidentally, BitConverter has a different (and better) implementation of the conversions than the ones above:
public static unsafe byte[] GetBytes(int value)
{
byte[] buffer = new byte[4];
fixed (byte* numRef = buffer)
{
*((int*)numRef) = value;
}
return buffer;
}
public static unsafe int ToInt32(byte[] value, int startIndex)
{
// NOTE: Removed argument validation for brevity
fixed (byte* numRef = &(value[startIndex]))
{
if ((startIndex % 4) == 0)
{
return *(((int*)numRef));
}
if (IsLittleEndian)
{
return (((numRef[0] | (numRef[1] << 8)) | (numRef[2] << 0x10)) | (numRef[3] << 0x18));
}
return ((((numRef[0] << 0x18) | (numRef[1] << 0x10)) | (numRef[2] << 8)) | numRef[3]);
}
}
The moral of the story? If you can't find what you need in the BCL - you probably haven't looked hard enough ;)