OneBite.Dev - Coding blog in a bite size

Count Array's Length In C#

Code snippet for how to Count Array's Length In C# with sample and detail explanation

In C#, arrays are crucial data structures which are commonly used to store multiple values in a single data unit. This article demonstrates how to count the length of an array correctly using C#, giving you a clear understanding of the process with the help of an easy-to-follow example and step-by-step instructions.

Code snippet: Count Array’s Length

using System;

class Program
{
    static void Main()
    {
        int[] array = {1, 2, 3, 4, 5}; // declare and initialize the array

        Console.WriteLine("The length of the array is " + array.Length); // prints length of the array
    }
}

Code Explanation for Count Array’s Length

Here’s how the above-mentioned C# code works:

  1. Include the System namespace: The first line of the code using System;, which includes the System namespace. The System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions.

  2. Declare the class: class Program, where ‘Program’ is the name of the class. In our case, a simple class is created named ‘Program’.

  3. Define the main method: static void Main(). This is the entry point of the program from where the execution begins.

  4. Declare and initialize the array: ‘int[] array = {1, 2, 3, 4, 5};‘. In this line, an integer array is declared and initialized with the values 1, 2, 3, 4, and 5.

  5. Get the length of the array: ‘array.Length’. This is a property of the array class in C# that returns the total number of elements in all the dimensions of the array.

  6. Print the length of the array: ‘Console.WriteLine(“The length of the array is ” + array.Length);‘. This line prints the length of the array to the console.

That’s about it. You’ve now learned how to count the length of an array in C#. Be sure to practice regularly to solidify your understanding.

c-sharp