Arrays

3) Array.

An array is an indexed set of objects, all of the same type. An array is fine for storing a fixed list of values or relerenres. The two particular characteristics of an array are that it contains a fixed number of items in a definite order.

As an example, imagine that for some reason we need to store the months of the year. There are twelve months and there will always be twelve months, that’s the fixed size, and the months also have a specific order. February always comes after January, March always comes after February, April always comes after March, and so on.

And for the first code demo, I’ll use the months of the year as an example to show how to instantiate an array and display all the items in it.

So I’m in Visual Studio with a new created console app. If   I wanted a single string, I would do something like this,

and then initialize it with the text I want

but I said we want all of the months of the year so that’s twelve strings so we need a collection of strings.
I will write the code we need now. And let’s analyze it after writeing.

I’m declaring the type as string followed by square brackets. Those square brackets are crucial. They are what tells the compiler that this is not a single string, but an array of strings or of whatever type is in front of the square brackets.

An array can be initialized when it is creating by providing a list of values
bounded by curly braces.

To initialize the array, you can see that I’ve listed out all the twelve strings
that will go in it, separated by commas. And I’ve got curly braces around the whole set of strings, and because this whole thing is one single C# statement, there’s a semicolon at the end.

There are other ways to initialize an array, which I’ll cover in the next module, but this is the simplest way if you know up front what data will go in the array.

So that will do us for now.