Create An Array With C# .NET

In this blog post, we are going to create an Array with C# .NET console application.

Without going into too many details about arrays, the most important part is that they are beneficial and handy to use and create when needed.

Create Console

Let’s start with creating a console application using the Dotnet CLI with the following command.

dotnet new console array

Once the console app has been created, go ahead and open the Program.cs file and copy the following code.

Create Array

In the code below, I am creating an array of integers called myarray with 20 items.

After creating the array, I add 1331 to item number 10 (Remember that the array starts at 0). In the next line, I’m printing item 10.

The for loop goes over the array, writes the value in variable x, and prints all the items.

using System;
namespace array
{
    class Program
    {
        static void Main(string[] args)
        {
            int [] myarray = new int [20];
             myarray [10] = 1331 ; 
             Console.WriteLine (myarray[10]);

             for (int x = 0; x < myarray.Length; x++)
             {
             myarray [x] =  x ;
             Console.WriteLine(myarray[x]);    
             }
        }
    }
}

To run and test the array, I will build and run the application using the following command.

dotnet run array

Published
Categorized as C#

Leave a comment

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