Home

Our Company

What's New?

Products

Purchase

Contact
Copyright Layers of Meaning All Rights Reserved
Welcome back! This is the sixth episode in the "C# Programming for Absolute Beginners" course. So far, we have learned about the most important features of C#, we have installed the free Visual Studio Community Edition IDE, and we have created our first Windows Forms application. Then, we have played with MessageBox controls, and we went through all the C# variables, using practical examples for each one of them.

This tutorial will discuss arrays, which are nothing more than collections of variables of the same type. So, let's create a new Windows Forms project, and then add a button to it. Then, double click the button to display the code associated to it.
C# Programming for Absolute Beginners
Working with C# Arrays - FREE SAMPLE
We will create a string array; it can only store arrays, but it can store as many arrays as we need it to. Here's a typical string array definition:

string[] fruits = {"tomato", "plum", "apple", "orange"};

Yes, "tomato" is a fruit indeed :)

We can access each array element using its index. The first element has an index value of zero, the second one has an index value of one, and so on. So, to access the apple, we would use fruits[2], get it?

Here's a quick example. Copy and paste the two lines of code below into our button1_Click function, and then run the project.

string[] fruits = {"tomato", "plum", "apple", "orange"};
MessageBox.Show(fruits[2]);
But what happens if you want to populate the string later on, by using data that is input by the end users? In this case, you should define the string this way:

string[] vegetables = new string[15]; // create a string array that can hold up to 15 elements

The elements of any string array that was created this way are empty; however, we can assign them the desired strings anytime we need to, by using a line of code that looks like this:

vegetables[0] = "cucumber";

Here's an example that accesses the first element in the "vegetables" string, displaying its content on the screen.
You can also create arrays using numerical values, of course. Here's the typical definition for an array of integers.

int[] grades = {8, 7, 10, 6, 9, 5};

The following example shows how you can access any of the array elements and display its value on the screen using a MessageBox.
As you already know from the fourth tutorial in this series, we can't use MessageBox to display numbers, so we have to convert the number to an array using the ToString() function.

You can create similar arrays for floats, doubles, etc.

This concludes the sixth episode in the "C# Programming for Absolute Beginners" tutorial. Check out the next tutorial, which will discuss C# lists.

See the outline of the entire C# Programming for Absolute Beginners course.