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 in C#
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.
using System;
namespace ObjectArray
{
class Program
{
static void Main(string[] args)
{
object[] array=new object[5]{1,1.1111,"Sharad",'c',2.79769313486232E+3};
foreach (var value in array)
{
Console.WriteLine(value);
}
Console.ReadKey();
}
}
}
Output
Dynamic Array in C#
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 of Dynamic Array
List<data type> name= new List<data type>();
e.g;
List<int> list=new List<int>();
Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DynamicArray
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to C-sharpcorner");
List<int> list=new List<int>();
list.Add(1);
list.Add(10);
list.Add(4);
list.Add(0);
int size = list.Count;
for (int i = 0; i < list.Count; i++)
Console.WriteLine(list[i]);
list.Sort();
Console.WriteLine("Sorted list values");
for (int i = 0; i < list.Count; i++)
Console.WriteLine(list[i]);
Console.ReadKey();
}
}
}
Output