Resizing Arrays in C# with Examples

In C#, you can resize an array using the Array.Resize<T> method. This method allows you to change the number of elements in a one-dimensional array to a specified new size. Let’s explore how it works and see some examples.

The Array.Resize<T> Method

The Array.Resize<T> method is defined as follows:

public static void Resize<T>(ref T[] array, int newSize);
  • T: The type of the elements in the array.
  • array: The one-dimensional, zero-based array to resize, or null to create a new array with the specified size.
  • newSize: The size of the new array.

Examples

Let’s look at some examples to understand how resizing affects an array.

1. Resizing to a Larger Size

Suppose we have the following string array:

string[] myArr = { "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog" };

We can resize this array to a larger size (five elements larger):

Array.Resize(ref myArr, myArr.Length + 5);

After resizing, the array contains the following values:

2. Resizing to a Smaller Size

Now let’s resize the array to a smaller size (four elements):

Array.Resize(ref myArr, 4);

After resizing, the array contains the following values:

"The", "quick", "brown", "fox"

Remarks

Remember that Array.Resize<T> provides a convenient way to adjust the size of an array dynamically during program execution.๐Ÿ˜Š


Similar Articles