This design pattern shows how to copy byte arrays, and convert an array to an ArrayList object that can be more flexibly manipulated.
// required for ArrayList class
using System.Collections;
private ScriptHelper helper = new ScriptHelper();
public void SendBytes()
{
// prepare a byte array: the array size is fixed
byte[] bytes = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05 };
ProcessBytes( bytes );
}
private void ProcessBytes( byte[] bytes )
{
// can't change the size of a byte array: can create a new larger array and copy the first one
byte[] moreBytes = new byte[ bytes.Length + 3 ];
bytes.CopyTo( moreBytes, 0 );
// we can only fill the additional bytes we added
moreBytes[ moreBytes.Length - 3 ] = 0x06;
moreBytes[ moreBytes.Length - 2 ] = 0x07;
moreBytes[ moreBytes.Length - 1 ] = 0x08;
// display each byte value of the array
for( int i = 0; i < moreBytes.Length; i++ )
{
helper.Logger.Debug( String.Format( "byte {0} = {1:X2}", i, moreBytes[i] ) );
}
// it's easier to convert the array to an ArrayList
ArrayList list = new ArrayList( bytes );
ProcessArrayList( list );
}
private void ProcessArrayList( ArrayList list )
{
// now we can easily add as many extra bytes as we need
list.Add( 0x06 );
list.Add( 0x07 );
list.Add( 0x08 );
list.Add( 0x09 );
list.Add( 0x0A );
// display each item of the ArrayList
for( int i = 0; i < list.Count; i++ )
{
helper.Logger.Debug( String.Format( "item {0} = {1:X2}", i, list[i] ) );
}
}
This design pattern:
creates a byte array with five elements, calls a method passing the array,
the ProcessBytes method allocates a new byte array in size equal to the length of the original array plus 3,
copies the original array to the new array, and fills in the extra three bytes,
loops through the bytes in the new array and displays each byte's value in hex format.
converts the byte array to an ArrayList, calls a method passing the ArrayList,
the ProcessArrayList method adds five more bytes to the list, there is no need to specify the final or desired size,
loops through elements in the list and displays each byte's values in hex format.