how to Increase the length of an array at runtime?

QuestionsCategory: C#how to Increase the length of an array at runtime?
Himanshu SHimanshu S asked 1 year ago

In .NET (C#), an array isn’t resizable. how to Increase the length of an array at runtime?

1 Answers
Best Answer
Mahesh DeshmaneMahesh Deshmane answered 1 year ago

Solution 1:
Starting with .NET Framework 3.5, for one-dimensional arrays you can use Array.Resize<T> method:

var arr1 = new[] { "Cat", "Monkey", "Dog" };
Array.Resize(ref arr1, 5);

This will increase arr1 size to 5 initial it was 3
Solution 2:
You can use System.Collections.Generic.List<T> which provides a resizable collection which also has a .ToArray() method to return an ordinary array if you need it.

var list = new List<string> { "Dog", "Tiger", "Cheetah" };

var arr =  list.ToArray();

Solution 3:
You can use System.Collections.ArrayList as it Implements the IList interface using an array whose size is dynamically increased as required.

var arr = new ArrayList {"Dog", "Tiger", "Cheetah" };