OneBite.Dev - Coding blog in a bite size

Get The First Element Of Array In C#

Code snippet for how to Get The First Element Of Array In C# with sample and detail explanation

In computer programming and software development, arrays play a significant role. This article provides a simple and easy guide to retrieving the first element of an array in C# programming language.

Code snippet for Getting the first element of Array

Here is a straight forward code snippet to get the first element of an array in C#:

static void Main(string[] args)
{
    int[] array = new int[5] {10, 20, 30, 40, 50};

    Console.WriteLine("First element of the array is: " + array[0]);

    Console.ReadKey();
}

Code Explanation for Getting the first element of Array

Let’s do a step-by-step explanation of the above code:

  1. Step 1 - Array Declaration: int[] array = new int[5] {10, 20, 30, 40, 50}; This line of code declares an integer array with five elements. The array is initialized with the values 10, 20, 30, 40, and 50.

  2. Step 2 - Fetch the First Element: Console.WriteLine("First element of the array is: " + array[0]); In the C# programming language, array indices start at 0. So, to fetch the first element of an array named ‘array’, we just need to write array[0]. This returns the first element of our array.

  3. Step 3 - Output The Result: The first element of the array is then printed out on the console.

  4. Step 4 - Await User Input: Console.ReadKey(); This line of code tells the system to wait for a key to be pressed before the console window closes. This gives us a chance to see the output before the program ends.

That’s all! You can see that getting the first element of an array in C# is quite simple and straightforward. All the best as you continue your journey in mastering C#!

c-sharp