Object and Dynamic Array in C#

Introduction

An Array is a type that holds multiple variables of one type, allowing an index to access the individual values. It is possible to store an array holding multiple variables of multiple types using an object type array.

Object Arrays


An object array is versatile. They can store an element of various types in a single collection.

Example

An example that shows how to store an element of a different type in a single array is as in the following:

  1. using System;  
  2. namespace ObjectArray  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             object[] array=new object[5]{1,1.1111,"Sharad",'c',2.79769313486232E+3};  
  9.             foreach (var value in array)  
  10.             {  
  11.                 Console.WriteLine(value);  
  12.             }  
  13.             Console.ReadKey();  
  14.         }  
  15.     }  
  16. }  
Output

object-array-in-c-sharp.gif

Dynamic Array


Static arrays have the disadvantage that if you have not used a full array then it will always use the same size as was defined during its declaration.  We usually need to have an array that we would not know the values of or how many of them exist. For that  we can use a dynamic array. A Dynamic Array defines a size of the array at runtime, but then makes room for new elements in the array during execution.

Declaration and Initialization

  1. List<data type> name= new List<data type>();  
  2. e.g;  
  3. List<int> list=new List<int>();  

Example

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. namespace DynamicArray  
  6. {  
  7.    class Program  
  8.    {  
  9.        static void Main(string[] args)  
  10.        {  
  11.            Console.WriteLine("Welcome to C-sharpcorner");  
  12.            List<int> list=new List<int>();  
  13.            list.Add(1);  
  14.            list.Add(10);  
  15.            list.Add(4);  
  16.            list.Add(0);  
  17.            int size = list.Count;  
  18.            for (int i = 0; i < list.Count; i++)  
  19.            Console.WriteLine(list[i]);  
  20.            list.Sort();  
  21.            Console.WriteLine("Sorted list values");  
  22.            for (int i = 0; i < list.Count; i++)  
  23.            Console.WriteLine(list[i]);  
  24.            Console.ReadKey();  
  25.     }  
  26.   }  
  27. }  
Output

dynamic-array-in-c-sharp.gif