Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do you find the length of an array in C#?
To find the length of an array in C#, use the Length property (not a method). The Length property returns the total number of elements in the array as an integer value.
Syntax
Following is the syntax for using the Length property −
int length = arrayName.Length;
Parameters
arrayName − The array whose length you want to find
Return Value
The Length property returns an int value representing the total number of elements in the array.
Example
Let us see an example −
using System;
class Program {
static void Main() {
int[] arr = new int[10];
// finding length
int arrLength = arr.Length;
Console.WriteLine("Length of the array: " + arrLength);
}
}
The output of the above code is −
Length of the array: 10
Above, we have an array −
int[] arr = new int[10];
Now to find the length, we used the Length property −
int arrLength = arr.Length;
Using Length with Different Array Types
Example
using System;
class Program {
static void Main() {
// Integer array
int[] numbers = {1, 2, 3, 4, 5};
Console.WriteLine("Integer array length: " + numbers.Length);
// String array
string[] names = {"Alice", "Bob", "Charlie"};
Console.WriteLine("String array length: " + names.Length);
// Double array
double[] prices = {10.5, 20.0, 15.75, 8.99};
Console.WriteLine("Double array length: " + prices.Length);
}
}
The output of the above code is −
Integer array length: 5 String array length: 3 Double array length: 4
Multidimensional Arrays
For multidimensional arrays, the Length property returns the total number of elements across all dimensions −
Example
using System;
class Program {
static void Main() {
// 2D array: 3 rows, 4 columns
int[,] matrix = new int[3, 4];
Console.WriteLine("2D array total elements: " + matrix.Length);
// Getting dimensions
Console.WriteLine("Number of rows: " + matrix.GetLength(0));
Console.WriteLine("Number of columns: " + matrix.GetLength(1));
}
}
The output of the above code is −
2D array total elements: 12 Number of rows: 3 Number of columns: 4
Conclusion
The Length property in C# provides a simple way to find the number of elements in an array. It works with all array types and returns the total element count for multidimensional arrays. Remember that Length is a property, not a method, so no parentheses are needed.
