[C#] Two Easy Tricks to Play with Byte Array Using Buffer.BlockCopy

A lot of times when I have to feed some APIs with byte array(byte[]), I got myself confused during converting what I have in hand(usually a string or even, a string array) to what I want it to be. There are certainly a lot of ways you could conduct this convention, and most of them works fairly well in terms of performance and space consumption. While putting these two criteria's aside, here're two simple and self-explained helper methods that will do the trick:

 static byte[] ConvertToBytes(string inputString)
 {
 byte[] outputBytes = new byte[inputString.Length * sizeof(char)];
 Buffer.BlockCopy(inputString.ToCharArray(), 0, outputBytes, 0, outputBytes.Length);
 return outputBytes;
 }

In some other cases when you want to concatenate two byte arrays, while you don't want to bother doing the convention between strings. Here's a easy way of doing it, which also employs Buffer.BlockCopy. Note that it appends the Byte[] arrayB to the end of Byte[] arrayA:

 static byte[] AppendTwoByteArrays(byte[] arrayA, byte[] arrayB)
 {
 byte[] outputBytes = new byte[arrayA.Length + arrayB.Length];
 Buffer.BlockCopy(arrayA, 0, outputBytes, 0, arrayA.Length);
 Buffer.BlockCopy(arrayB, 0, outputBytes, arrayA.Length, arrayB.Length);
 return outputBytes;
 }