Array in C#

Updated on     Kisan Patel

An Array is a collection of values of a similar data type.

Array can be declared as –

<data type>[] <identifier> = new <data type>[<size of array>];

For Examples

int[] numbers = new int[10]

In above example, we have declared integer type array with size of 10.

The size of an array is fixed and must be defined before using it.

You can initialize array item either during the creation of an array or later by referencing array item, as shown here.

int[] nums = new int[5];
int[0] = 1;
int[1] = 2;
int[2] = 3;
int[3] = 4;
int[4] = 5;

Or

int[] nums = {1,2,3,4,5};

To Access the values stored in an Array variable, we can use the indexing operator as shown in below.

int[] nums = {10, 20, 30, 40};
int i = nums[3]; // here, i = 40
Note : The index values in Array start from 0. So if an array contains 5 elements, the first element would be at index 0.
using System;

namespace ConsoleApp
{
    class ArrayDemo
    {
        static void Main(string[] args)
        {
            string[] names = {"Kisan", "Ravi", "Devang", "Ujas" };
            int i = 2;

            Console.WriteLine("The {0} in names array at {1} position.", names[i], i);
        }
    }
}

The output of the above C# program…

c-sharp-array-demo


C#

Leave a Reply