The word buffer implies something that works directly on memory. In the C# language, buffering is basically a manipulation of unmanaged memory that is represented as arrays of bytes. Table 21.14 describes some members of the Buffer class. Let's look at an example of a program where we copy one array of data into another using the Array class, and then we will compare that with a Buffer class example doing the same thing.

Table 21.14: Buffer Class Members
In the System.Array class the Copy() member allows us to copy from one array to another. Let's take an array of five elements, Myarr1[5], initialized with the data 1, 2, 3, 4, 5 and another array of 10 elements, Myarr2[10], with the data 0, 0, 0, 0, 0, 6, 7, 8, 9, 10. In arrays, length refers to the number of elements in the array. In our example, Myarr1 has five elements, so the array length is 5, and Myarr2 has 10 elements, so the array length is 10. The Array class includes the Copy() method, which copies the contents of one array into another. It copies a range of elements from an array starting at the specified source index and pastes it to another array starting at the specified destination index. The Copy() method takes five parameters: source array, source index, destination array, destination index, and number of elements to copy.
The method Array.Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length) takes five parameters: first, the array that contains the data to copy; second, the index in the sourceArray at which copying begins; third, the array that receives the data; fourth, DestinationIndex, the index in the destinationArray at which storing begins; and, fifth, the number of elements to copy.
Listing 21.32 demonstrates the use of the Array.Copy() method. In the listing we perform Array.Copy(myarr1, 0, myarr2, 0, 5) for the following arrays:
int[] myarr1 = new int[5] { 1, 2, 3, 4, 5 };
int[] myarr2 = new int[10] { 0, 0, 0, 0, 0, 6, 7, 8, 9, 10 };
Listing 21.32: Using Array.Copy (array1buffer.cs)
using System;
public class Array1
{
public static void Main(string[] args)
{
int[] myarr1 = new int[5] { 1, 2, 3, 4, 5 };
int[] myarr2 = new int[10] { 0, 0, 0, 0, 0, 6, 7, 8, 9, 10 };
Console.Write("Before Array copy operation\n");
Console.Write("Myarr1 and Byte Length{0}\n", myarr1.Length);
foreach (int i in myarr1)
Console.Write("{0} \t", i);
Console.WriteLine("\nMyarr2 and Byte Length:{0} \n", myarr2.Length);
foreach (int i in myarr2)
Console.Write("{0} \t", i);
Array.Copy(myarr1, 0, myarr2, 0, 5);
Console.Write("After Array copy operation\n");
Console.Write("Myarr1 :\n");
foreach (int i in myarr1)
Console.Write("{0} \t", i);
Console.WriteLine("\nMyarr2: \n");
foreach (int i in myarr2)
Console.Write("{0} \t", i);
Console.ReadLine();
}
}


Comments
Join the conversation! Your thoughts help the community grow.