What is Array.Length in C#?
Overview
Array.GetLength() in C# is an array property. It is used to get the number of elements, or the length, of an array. It can be used to get the length of an array of any dimension.
Syntax
public int Length { get; }
Syntax for getting the number of array elements in C#
Parameters
None. It is only called on an array.
Return value
The value returned is an integer value that is the total number of elements present in an array. It returns 0 if no elements are present.
Code example
// use Systemusing System;// using System.Collections.Generic;// create classpublic class ArrayClearance {// Main Methodpublic static void Main(){// Creating and initializing new the Stringint[] arr1 = {10, 20, 30, 40};char[] arr2 = {'E', 'd', 'p', 'r', 'e', 's', 's', 'o'};bool[] arr3 = {true, false};double[] arr4 = {};// print lenghts of arraysConsole.WriteLine(arr1.Length);Console.WriteLine(arr2.Length);Console.WriteLine(arr3.Length);Console.WriteLine(arr4.Length);}}
Explanation
- Lines 13-15: We create arrays of different data types.
- Line 16: We create an empty array.
- Lines 19-22: We print the lengths of the arrays on the console using the
Lengthproperty.