Intro to Arrays – Create Arrays and Access Elements
In this CSharp lecture we are going to cover arrays. Arrays enables us to save multiple objects of the same type within a variable.
Syntax for Arrays in CSharp
VariableType[] arrayname = {Content Position 0, Content Position 1, Content Position 2, Content Position 3, ...};
As you can see, the first position is not 1 but 0. In programming counting usually starts at 0.
You can declare arrays of different data types. Integer, string, double or other object arrays. We can e.g. make an array which is filled with objects of our car class from previous lectures.
Example for Arrays in CSharp:
class Program { public static void Main(string[] args) { int[] numbersArray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int[] numbersArray2 = { 3, 4, 5, 6, 7 }; for (int i = 0; i < numbersArray.Length; i++) { Console.WriteLine(numbersArray[i]); } for (int i = 0; i < numbersArray2.Length; i++) { Console.WriteLine(numbersArray2[i]); } } }
Here we have created two different arrays to show that the index i in our For loops, is not the the same number as the content of the array in the indexes position. In the first For loop the index and content are the same, but in the second one not. So the first For loop ensures that the numbers 0 to 9 are output and the second loop outputs 3 then 4 then 5 etc.. This is because in our numbersArray2 the position 0 corresponds to the number 3.
So now you have seen how to create an array and how to access it. When accessing you simply have to use the arraysname[position of the content you want to access]
Here we used a quite simple example with numbers. But you can use it in much more complex situations. e.g. for the purpose of a card game, an array would be ideal to use it for a deck of cards . You will learn more about arrays in this chapter.