Arrays in C#

You can use variables to store small number of values. But if you have large data, it is not convenient use simple variables. Imagine you have to store names of all the students in a school and they are hundreds in numbers; it would not be wise to create hundreds of variables. In such cases, a collection of variables that can be declared at once will be handy. Array is basically such a collection. It can store data of similar types in the form of  a collection. Let us see how arrays are created, how data assigned to arrays and how items can be accessed within the array.

using System;
namespace CSharpTutorials {

    class Tutorial {
        static void Main(string[] args) {
            // creating an array
            int[] array = new int[5];

            // another way to create array
            int[] array2 = { 10, 25, 35, 45, 55 };

            //accessing array elements
            Console.WriteLine(array2[3]);

            //assigning values to array index
            array2[3] = 100;
            Console.WriteLine(array2[3]);
            Console.ReadKey();
        }
    }
}

Download the code

Declaring an array is simple. You first specify the type of array, followed by opening and closing bracket and then the name of the array. In above example, an array of type integer and  named “array” has been declared.

Declaring an array is one thing but creating space for the array in the memory is another. This is done via new keyword followed by opening and closing bracket and the type of the array.

Once an array is created the next step is to assign elements to an array. It is imperative to mention here that an array has a zero based index which means that the first element of array is stored at the 0th index while the last element is stored and k-1st index where ‘k’ is the size of the array.

To assign value to an array, write the name of the array followed by the opening and closing brackets. Inside the brackets specify the index at which you want to store the element and simply assign it some value using equals operator. To access elements within the array, you only have to write the name of the array, followed by the index at which element is located.

Accessing array elements using for each loop

Here is a cool trick, if you want to iterate all the elements within an array, you can use foreach loop in the following way.

using System;
namespace CSharpTutorials {

    class Tutorial {
        static void Main(string[] args) {

            int[] numarray = { 10, 25, 35, 45, 55, 60, 33, 57 };
            foreach (int num in numarray) {
                Console.WriteLine(num);
            }
            Console.ReadKey();
        }
    }
}

Download the code

<<< Structures in C#Functions in C# >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .