How to copy a range of elements from one array to another in c#

 
If you want to copy a range of the elements from one array to another then we can use Array.ConstrainedCopy Method. In this article i will try to understand that how we can copy a range of elements from one array to another.

http://msdn.microsoft.com/en-us/library/system.array.constrainedcopy%28v=vs.90%29.aspx#Y51

Summery:

public static void ConstrainedCopy(
	Array _sourceArray,
	int _sourceIndex,
	Array _destinationArray,
	int _destinationIndex,
	int _length
)

where

_sourceArray: The Array that contains the data to copy.
_sourceIndex: A 32-bit integer that represents the index in the sourceArray at which copying begins.
_destinationArray: The Array that receives the data.
_destinationIndex: A 32-bit integer that represents the index in the destinationArray at which storing begins.
_length: A 32-bit integer that represents the number of elements to copy.

Example:

Suppose if you have an array Arr1 with eight elements:

Arr1[0] = “a”
Arr1[1] = “b”
Arr1[2] = “c”
Arr1[3] = “d” //need to copy to array Arr2
Arr1[4] = “e” //need to copy to array Arr2
Arr1[5] = “f” //need to copy to array Arr2
Arr1[6] = “g”
Arr1[7] = “h”

and we need to copy a range (4th to 6th) of elements in array Arr2

in this case source Array will be Arr1, sourceIndex willbe 3, destinationArray will be Arr2, destinatioindex will be 0 and length will be 3(total number of elements need to copied).

see the example:

      private void CopyElements()
        {
            string[] Arr1 = { "a", "b", "c", "d", "e", "f", "g","h" };
            string[] Arr2 = new string[3];
            Array.ConstrainedCopy(Arr1, 3, Arr2, 0, 3);
        }

Output will be:

Arr2[0] = “d”
Arr2[1] = “e”
Arr2[2] = “f”