Array.Constrainedcopy() Method In C#

In this guide, we will explore the Array.ConstrainedCopy method in C# along with its syntax, parameters, and demonstrations.

What is the Array.ConstrainedCopy?

The Array.ConstrainedCopy function is employed for transferring a selection of elements from one array to another, guaranteeing the process is executed correctly and stays within the defined limits. This function proves valuable when dealing with arrays, especially in scenarios where upholding memory integrity and preventing buffer overflows are paramount.

Syntax:

It has the following syntax:

Example

public static void ConstrainedCopy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)

Parameters:

  • sourceArray: It is the source array from which elements will be copied.
  • sourceIndex: The sourceArray beginning index from where copying begins.
  • destinationArray: The place of the copied elements inside the destination array.
  • destinationIndex: The index in the destinationArray where copying starts at this point.
  • length: The number of elements that must be copied from the source array to the destination array.
  • Example:

Let's consider a scenario to demonstrate the Array.ConstrainedCopy function in C#.

Example

using System;
class Demo
{
    static void Main()
    {
        // Source Array
        int[] source_Array = { 14, 25, 32, 47, 85, 93 };
        // Destination array
        int[] destination_Array = new int[6];
        try
        {
            // Copy elements from sourceArray to destinationArray
            Array.ConstrainedCopy(source_Array, 0, destination_Array, 0, 6);
            // Displaying the elements of destinationArray
            Console.WriteLine("Destination Array:");
            foreach (var item in destination_Array)
            {
                Console.WriteLine(item);
            }
        }
        catch (ArgumentNullException e)
        {
            // Handle the ArgumentNullException (if sourceArray or destinationArray is null)
            Console.WriteLine("Error: " + e.Message);
        }
        catch (ArgumentOutOfRangeException e)
        {
            // Handle the ArgumentOutOfRangeException (if index or length parameters are out of range)
            Console.WriteLine("Error: " + e.Message);
        }
    }
}

Output:

Output

Destination Array:
14
25
32
47
85
93

Explanation:

By employing the Array.ConstrainedCopy method, this illustration showcases the secure transfer of elements between arrays while effectively managing any potential exceptions that might arise during the complete operation.

Exceptions:

There are a number of conditions under which exceptions may be thrown in the Array.ConstrainedCopy method. Some of these exceptional cases include:

1. ArgumentNullException:

It will happen if either the destinationArray or the sourceArray is null.

Example:

Let's consider a scenario to demonstrate the Array.ConstrainedCopy technique by utilizing the ArgumentNullException in C#.

Example

using System;
class Demo
{
    static void Main()
    {
        int[] sourceArray = null; // Null source array
        int[] destinationArray = new int[5];
        try
        {
            // Trying to copy elements from sourceArray to destinationArray
            Array.ConstrainedCopy(sourceArray, 0, destinationArray, 0, 4);
        }
        catch (ArgumentNullException e)
        {
            // Handle the ArgumentNullException
            Console.WriteLine("An error occurred: " + e.Message);
        }
    }
}

Output:

Output

An error occurred: The value cannot be null.
Parameter name: sourceArray

2. ArgumentOutOfRangeException

If the length is negative, it indicates that either the sourceIndex is below the lower boundary of the first dimension of the sourceArray, or the destinationIndex is below the lower boundary of the first dimension of the destinationArray.

Example:

Let's consider a scenario to demonstrate the Array.ConstrainedCopy method by utilizing an example involving the handling of an ArgumentOutOfRangeException in the C# programming language.

Example

using System;
class Demo
{
    static void Main()
    {
        int[] source_Array = { 1, 2, 3, 4, 5 };
        int[] destination_Array = new int[3]; // Destination array size is smaller
        try
        {
            // Trying to copy elements from sourceArray to destinationArray
            // The copy length (5) exceeds the size of the destinationArray
            Array.ConstrainedCopy(source_Array, 0, destination_Array, 0, 6);
        }
        catch (ArgumentOutOfRangeException e)
        {
            // Handle the ArgumentOutOfRangeException
            Console.WriteLine("Error Occured: " + e.Message);
        }
    }
}

Output:

Output

Unhandled Exception:
System.ArgumentException: length

Explanation:

As illustrated by these instances, the "Array.ConstrainedCopy" function raises exceptions if it comes across null arrays or if the length or index parameters fall outside allowed boundaries.

3. RankException

If the sourceArray and destinationArray possess varying dimensions.

Example:

Example

using System;
class Demo
{
    static void Main()
    {
        // Source array with rank 1 (single-dimensional array)
        int[] source_Array = { 1, 2, 3, 4, 5 };
        // Destination array with rank 2 (multi-dimensional array)
        int[,] destination_Array = new int[5, 1];
        try
        {
            // Trying to copy elements from sourceArray to destinationArray
            // TBecause sourceArray and destinationArray have different rankings; this will raise a RankException.
            Array.ConstrainedCopy(source_Array, 0, destination_Array, 0, 5);
        }
        catch (RankException e)
        {
            // Handle the RankException
            Console.WriteLine("Error Occured: " + e.Message);
        }
    }
}

Output:

Output

Error Occurred: Only single-dimension arrays are supported here.

Explanation:

In this instance, the following code exemplifies the process of managing a RankException in C# while moving elements between arrays of different dimensions utilizing the 'Array.ConstrainedCopy' technique.

4. ArgumentException

If the number of elements in the destinationArray from the destinationIndex exceeds the number of elements remaining in the sourceArray from the sourceIndex, the length should surpass the count of elements remaining in the sourceArray 'Or'.

Example:

Example

using System;
class Demo
{
    static void Main()
    {
        // Source Array
        int[] source_Array = { 1, 2, 3, 4 };
        // Destination array with insufficient space
        int[] destination_Array = new int[6];
        try
        {
            // Trying to copy elements from sourceArray to destinationArray
            // The length parameter (5) exceeds the available space in destinationArray
            Array.ConstrainedCopy(source_Array, 0, destination_Array, 0, 5);
        }
        catch (ArgumentException e)
        {
            // Handle the ArgumentException
            Console.WriteLine("Error Occurred!: " + e.Message);
        }
    }
}

Output:

Output

Error Occurred!: length

Input Required

This code uses input(). Please provide values below: