What is an Arrays in C#?An array is used to store a collection or series of elements. These elements will be of the same type.
So for example, if you had an array of Integer values, the array could be a collection of values such as [1, 2, 3, 4]. Here the number of elements in the array is 4.
Arrays are useful when you want to store a collection of values of the same type. So instead of declaring a variable for every element, you can just declare one variable.
This variable will point to an array or list of elements, which will be responsible for storing the elements of the array.
Let’s look at how we can work with arrays in C#. In our example, we will declare an array of Integers and work with them accordingly.
Note that all of the below code is being made to the Program.cs file.
Step 1) Declaring an array – The first step is to declare an array. Let’s see how we can achieve this by the below code example.
- The first part is the datatype. It specifies the type of elements used in the array. So in our case, we are creating an array of Integers.
- The second part [ ], which specifies the rank of the array. (The rank is a placeholder which specifies the number of elements the array will contain)
- Next is the Name of the array which in our case is ‘values’. Note you see a green squiggly underline, don’t worry about that. That is just .Net saying that you have declared an array, but not using it anywhere.
- First, we are setting the number of elements the array will hold to 3. So in the square brackets, we are saying that the array will hold 3 elements.
- Then we are assigning values to each element of the array. We can do this by specifying the variable name + the index position in the array.So values means that we are storing a value in the first position of the array. Similarly to access the second position, we use the notation of values and so on and so forth.
Note: – In Arrays, the index position starts from 0.
Code Explanation:-using System;
static void Main(string args)
This is the simple part wherein we just use the Console.WriteLine method to send each value of the element to the console.
Note that again, we are accessing each element with the help of the array variable name along with the index position.
If the above code is entered properly and the program is executed, the following output will be displayed.
From the output, you can see all the values of the array being displayed in the Console.