C# Arrays

C# Code Snippets Arrays
Share:

About

In this code snippet, we will learn how to use arrays in C#.

Arrays are like boxes, each box is accessible by a number called an index. They are zero-based. This means that the first box in the array has an index of 0, not 1.

When you make an array you have to specify the data type of the values it’s going to store. You also have to define the size of the array(how many values it can hold). Array are immutable meaning they can’t be resized once initialized(there are some workarounds). If you find yourself needing to resize an array consider using lists instead.

Arrays can have more than one “dimension”. You can imagine multidimensional arrays as a series of boxes within other boxes. Check out this post to see how to fill 1D, 2D and 3D arrays with data and print their contents.

Let’s see how to make and use arrays in the code example below.

Code:

using System;

namespace Arrays
{
    class Program
    {
        static void Main(string[] args)
        {
            //To make an array you first define the data type. 
            //Than you make a set of square brackets indicating it's an array you are declaring. 
            //Finally you name your array like you would a normal variable.
            int[] myArray;

            //Next we initialize our array like so. The number in the square brackets defines the size of the array.
            myArray = new int[3];

            //We can assign values to the array by using an index like so:
            //Note: Arrays are zero based(the first position starts at 0).
            myArray[0] = 1;
            myArray[1] = 10;
            myArray[2] = 100;

            //And we can retrieve a value from an array using an index like so:
            Console.WriteLine(myArray[1]);


            //Arrays can be of any data type, for example, a string array. 
            //They can have two, three or even more "dimensions".
            //We can declare and initialize an array in one line of code like so:
            string[,] mySecondArray = new string[5, 5];
            mySecondArray[0, 0] = "Hi.";

            Console.WriteLine(mySecondArray[0, 0]);

            Console.ReadLine();
        }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger