C# Basics – Arrays – Part 8

We introduce arrays in C# programming language. Arrays come in handy when there is a repetitive action needed upon values of the same data type.


Andraz Krzisnik
C# Basics – Arrays – Part 8

Arrays

It’s an often occurrence, that we are dealing with a bunch of data of the same data type. And in case we want to process each value in the same or similar way, arrays come in handy very much. Array is basically a group of values, which they all have their own index, or in other words, their own spot in this group.

Now each of this spots is a separate variable, and if we want to call a specific variable we need to write the name of the array it’s stored in, followed by an index number in square brackets.

int[] i = {1, 2, 3};

//Display a message window with first number in array
MessageBox.Show(i[0].ToString());

The first thing we need to do, when creating an array, is declaring it.

How do we do that?

We need to write the data type of values, this array will hold, followed by empty square brackets and a name of the array.

Now this isn’t all of it. If we want to use this array, we need to set the numbers of slots it will have. We do that with new command followed with the name of the data type and square brackets with a number of slots this array will be set to have.

Let’s demonstrate in code:

//Declared an array with 5 slots for integers
int[] i = new int[5]

//Third value is a sum of first and second numbers in the array
i[2] = i[0] + i[1]

//Add +1 to each variable in the array
for (int j; j < 5; j++)
{
    i[j]++;
}
Download Examples Next Chapter
Show Comments (0)

Comments

Related Articles

C# Basics

C# Basics – Random Numbers, Chars and Strings – Part 7

Random Numbers To generate a random number, we will use a constructor called Random. Then to generate a random number we will use either .Next() or .NextDouble() function. Random...

Posted on by Andraz Krzisnik
C# Tutorial

C# Tutorial: How To Use Gamma Correction

Gamma correction is a process, which allows you to set the brightness of screen. You can often run into this setting in video games, where you set the brightness of your screen...

Posted on by Andraz Krzisnik