Arrays

C#Arrays are basically a collection of items.  The items could be of any data type explicitly defined by you.  You can create an array of integer, double, string etc.  The arrays are extremely useful when you want to create collection of same set of data type items.  You can easily iterate and get the info about each item available in the array or you can excess them using their index.

There are 3 ways, which you can use to initialize an array.

using System;

namespace MyHelloWorld
{
    

    class Program
    {
        static void Main(string[] args)
        {
            //First  Array
            int[] items1 = new int[5];

            //Second Array
            string[] items2 = { "Robert", "Peter", "Pinto" };

            //Third Array
            string[] items3 = new string[] { "Robert", "Peter", "Pinto" };
        }
    }
}

 

First one, we have created an array of integer data type, in which you can insert 5 items.  The index of an array always starts from 0.  In this snippet, the index of array starts from 0 and ends at 4.  This means, the first value in this array will get the index of 0 and last the value will get the index of 4.

Second one, we have created an array of strings and assigned their values.  The number of items you assign at this point, will decide the size of the array, which is 3 now.

Third one,  we have created an array of strings using object initiliazer syntax, where you can directly assign the values to an array.   At compile time, C# compiler will assume that you have created an array of 3 items.