Find The Length Of An Array In C#
Code snippet for how to Find The Length Of An Array In C# with sample and detail explanation
Arrays in C# are fundamental data structures that allow you to store multiple values of the same type in a single variable. To manipulate these values efficiently, it’s often necessary to know the length of the array.
Code snippet for Finding the Length Of An Array
using System;
class Program {
static void Main(string[] args) {
int[] array = {1, 2, 3, 4, 5};
int length = array.Length;
Console.WriteLine("The length of the array is " + length);
}
}
Code Explanation for Finding the Length Of An Array
In this simple C# program, we are using the Length
property of an array to find its length. Here’s how it works:
-
using System;
: This is the first line of our program.System
is a namespace which contains the basic classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. We are using it here to useConsole
class defined inside it. -
class Program
: Here we’re declaring a class namedProgram
. All the codes are written inside this class. -
static void Main(string[] args)
: The Main method is the entry point of a C# console application. When the application is started, the Main method is the first method that is invoked. -
int[] array = {1, 2, 3, 4, 5};
: We declare an array of type integer and initialize it with five values. -
int length = array.Length;
: The ‘Length’ property of array object is used to get the total number of elements in the array. We’re storing that value in a variablelength
. -
Console.WriteLine("The length of the array is " + length);
: In the end, we are displaying the length of an array using the Console.WriteLine method.
When you run the program, it will display “The length of the array is 5”, as we have five elements in the array that we defined. The Length
property is a very handy feature of C# arrays and can save a lot of time and coding effort.