OneBite.Dev - Coding blog in a bite size

Create An Array Of Number In C#

Code snippet for how to Create An Array Of Number In C# with sample and detail explanation

Array is a powerful feature of C# that can store multiple elements of the same data type, making it an essential tool for many programmers. This article provides a step-by-step tutorial about how to create an array of numbers in C#.

Code snippet: Creating an Array in C#

int[] numArray = new int[5] {1, 2, 3, 4, 5};
foreach (int i in numArray)
{
    Console.WriteLine(i);
}

Code Explanation for Creating an Array in C#

The above snippet demonstrates how to create a simple array of integers in C#. Here’s a breakdown of what each part of the code does:

  1. int[] numArray = new int[5] {1, 2, 3, 4, 5}; initiates an array named numArray. The ‘new’ keyword is using to instantiate the array. The number within the square brackets, [5], indicates the size of the array and {1, 2, 3, 4, 5} are the values assigned to the array.

  2. foreach (int i in numArray) is a “foreach” loop. It’s used here to iterate over the elements of the numArray.

  3. Within the loop, Console.WriteLine(i) prints each element from the array to the console window.

That wraps up this quick tutorial on how to create an array of numbers in C#, showcasing how to both create and utilise an integer array.

c-sharp