In this blog post, we will learn how we can get the length of array in C#.

This is really easy and we will see how we can use the .Length property on any array that you want to get the length or the count of elements for.

Let's see how we can get the length of array using a code example.

 

 

Length Of Array Using Array.Length

// Initialize a New String Array With Default Values var arrayofColors = new string[] { "red", "green", "orange" }; // Get Length Of Array Using Array.Length var countOfArrayOfColors = arrayofColors.Length; // Display Console.WriteLine(countOfArrayOfColors);

 

Result:

3

 

This example is just small easy code example in which we can clearly see the length of the Array.

But what if this Array had thousands of elements in it. This is where the Array.Length property comes in handy.

We can use the .Length property on the Array to dynamically get the length of Array or the count of elements in Array.

 

 

Usage Of Array.Length To Get Length Of Array- More Code Examples

When we get the length of the Array, we can use the length and use it in if else statements or, we can use it to iterate a for loop and do something in the loop.

Here's a code example of the Array.Length in an if else loop.

// Initialize a New String Array With Default Values var arrayofColors = new string[] { "red", "green", "orange" }; if (arrayofColors.Length == 0) { Console.WriteLine("The color array is empty."); } else { Console.WriteLine("We have some colors in the array to play with."); }

 

Here's another code example of the Lenth property on the Array and this time we will use it in a for loop.

// Initialize a New String Array With Default Values var arrayofColors = new string[] { "red", "green", "orange" }; for (int i = 0; i < arrayofColors.Length; i++) { Console.WriteLine(arrayofColors[i]); } // Result: red green orange