Introduction
An Array in C# is a collection of elements with their unique index to access them. It is a sequential collection and only supports variables with similar data types. All the elements in the array get stored in the contiguous memory location. The size of the array is fixed and static. The default value of an element in a numeric array is 0 (Zero). The index of an array always starts from 0 and ends with the index n-1(n is the length of the array). Let’s learn about the object and dynamic arrays in this article.
Object arrays
The collection of different elements with different data types in a single array is called an object array. They are versatile and increase the complexity of a program. The object array contains the references to any derived type instances as elements. Let’s learn how to create an object array and insert values into it.
using System;
class ObjectArrayExample {
public static void main()
{
// Type 1
object[] arr1 = new object[4]{5, “codingNinjas”, 25.2, ‘E’};
//Type 2
object[] arr2 = new object[4];
arr2[0] = 5;
arr2[1] = “codingNinjas”;
arr2[2] = 25.2;
arr2[3] = ‘E’;
// Print the elements
Console.WriteLine(“First array:”);
foreach(var item in arr1)
{
Console.WriteLine(item);
}
Console.WriteLine(“Second array:”);
foreach(var ele in arr2)
{
Console.WriteLine(ele);
}
}
}
Output
First array:
5
codingNinjas
25.2
E
Second array:
5
codingNinjas
25.2
E
We can declare and initialize the elements in an array in two ways, as shown in the code above. We can initialize the values while declaring using the braces or assign the values to elements individually later. Both the arrays will give the same result when we print them.
Must Read IEnumerable vs IQueryable.