How to create arrays dynamically in C#?


Dynamic arrays are growable arrays and have an advantage over static arrays. This is because the size of an array is fixed.

To create arrays dynamically in C#, use the ArrayList collection. It represents ordered collection of an object that can be indexed individually. It also allows dynamic memory allocation, adding, searching and sorting items in the list.

The following is an example showing how to create arrays in dynamically in C#.

Example

 Live Demo

using System;
using System.Collections;
namespace CollectionApplication {
   class Program {
      static void Main(string[] args) {
         ArrayList al = new ArrayList();
         al.Add(99);
         al.Add(47);
         al.Add(64);
         Console.WriteLine("Count: {0}", al.Count);
         Console.Write("List: ");
         foreach (int i in al) {
            Console.Write(i + " ");
         }
         Console.WriteLine();
         Console.ReadKey();
      }
   }
}

Output

Count: 3
List: 99 47 64

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 23-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements