Array.Constrainedcopy() Method In C#

In this article, we will discuss the Array.ConstrainedCopy method in C# with its syntax, parameters, and examples.

What is the Array.ConstrainedCopy?

The Array.ConstrainedCopy method is used to copy a range of elements from one array to another while ensuring that the operation is carried out properly and within the specified boundaries. This method is very helpful when working with arrays where maintaining memory safety and avoiding buffer overflows are critical.

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 us take an example to illustrate the Array.ConstrainedCopy method 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:

Using the Array.ConstrainedCopy method, this example demonstrates how to safely copy elements across arrays while handling any possible exceptions that may occur throughout the entire process.

Exceptions:

There are several exceptions in the Array.ConstrainedCopy method. Some of the exceptions are as follows:

1. ArgumentNullException:

It will occurs, if either the destinationArray or the sourceArray is null.

Example:

Let us take an example to illustrate the Array.ConstrainedCopy method using 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 length is less than 0, either the sourceIndex is less than the lower bound of the sourceArray's first dimension, or the destinationIndex is less than the lower bound of the destinationArray's first dimension.

Example:

Letus take an example to illustrate the Array.ConstrainedCopy method using ArgumentOutOfRangeException in C#.

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 these examples demonstrate, the "Array.ConstrainedCopy" method throws exceptions when it encounters null arrays or when the length or index parameters are not within a permitted range.

3. RankException

If the sourceArray and destinationArray have different ranks.

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 example, this code demonstrates how to handle a RankException in C# when transferring elements between arrays of various rankings using the 'Array.ConstrainedCopy' method.

4. ArgumentException

Suppose the length exceeds the count of elements from destinationIndex to the end of destinationArray. In that case, the length should exceed the count of elements from sourceIndex to the end of 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: