OneBite.Dev - Coding blog in a bite size

Declare An Array In C#

Code snippet for how to Declare An Array In C# with sample and detail explanation

In C#, an array is an essential aspect of data management in the programming process. This article will guide you on how to declare an array in C# using a straightforward example code snippet and provide an explanation of the code.

Code Snippet: Declaring An Array in C#

using System;

class Program
{
   static void Main(string[] args)
   {
      int[] numbers = new int[5] {1, 2, 3, 4, 5};
      foreach (var number in numbers)
      {
         Console.WriteLine(number);
      }
      Console.ReadKey();
   }
}

Code Explanation for Declaring An Array in C#

In the code snippet above, we first ensure that we’re using the System namespace. This package is essential as it contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions.

The keyword ‘class’ is used to declare our class ‘Program’, which signifies a blueprint from which we can create objects.

Our Main method is where the execution of the program starts in C#. It should always be included in any C# program.

We then declare an integer array named ‘numbers’. The line ‘int[] numbers = new int[5] {1, 2, 3, 4, 5};’ tells the program that we are declaring an array of integer type. The square brackets after the int keyword denote that it’s an array. The numbers within the curly brackets are the elements of the array.

The ‘foreach’ loop is then used to iterate over the array ‘numbers’, displaying each number on the console. This ‘Console.WriteLine(number);’ means that for each number in the ‘numbers’ array, write it in a new line on the console.

Finally, we use ‘Console.ReadKey();’ to prevent the console from closing immediately once the program has finished executing. This step allows us to view the results.

In summary, the example provided provides a clear picture of how to declare and use an array in C#. With arrays, you can keep your code efficient and organized, especially when dealing with large data inputs.

c-sharp