find the length of an array in csharp

In C#, the length of an array can be found using the .Length property. Here's an example:

main.cs
int[] numbers = {1, 2, 3, 4, 5};
int length = numbers.Length;
Console.WriteLine(length); // Output: 5
102 chars
4 lines

Alternatively, you can also use the .Count() extension method from the System.Linq namespace:

main.cs
int[] numbers = {1, 2, 3, 4, 5};
int count = numbers.Count();
Console.WriteLine(count); // Output: 5
101 chars
4 lines

Note that the .Count() method works not only for arrays but also for other enumerable collections. Another alternative is using the sizeof operator, but this is only applicable to arrays of value types:

main.cs
int[] numbers = {1, 2, 3, 4, 5};
int size = sizeof(int) * numbers.Length;
Console.WriteLine(size); // Output: 20 (assuming sizeof(int) is 4 bytes in the current platform)
171 chars
4 lines

related categories

gistlibby LogSnag