0
0
CsharpHow-ToBeginner · 3 min read

How to Find Length of Array in C# - Simple Guide

In C#, you find the length of an array using the Length property. For example, array.Length returns the number of elements in the array.
📐

Syntax

Use the Length property on an array variable to get the total number of elements it contains.

  • array: Your array variable.
  • Length: Property that returns the size of the array as an integer.
csharp
int length = array.Length;
💻

Example

This example shows how to create an array and print its length using the Length property.

csharp
using System;

class Program
{
    static void Main()
    {
        int[] numbers = { 10, 20, 30, 40, 50 };
        Console.WriteLine("Length of array: " + numbers.Length);
    }
}
Output
Length of array: 5
⚠️

Common Pitfalls

Some common mistakes when finding array length in C# include:

  • Trying to use Count() method which is for collections, not arrays.
  • Confusing Length with the last index (which is Length - 1).
  • Using Length on a null array causes a NullReferenceException.
csharp
/* Wrong way: Using Count() on array */
// int count = array.Count(); // This causes error unless using LINQ

/* Right way: Use Length property */
int length = array.Length;
📊

Quick Reference

Remember these quick tips when working with array length in C#:

  • Use array.Length to get the number of elements.
  • Array indices go from 0 to Length - 1.
  • Length is a property, not a method (no parentheses).

Key Takeaways

Use the Length property to get the number of elements in a C# array.
Array indices start at 0, so the last index is Length minus one.
Length is a property, so do not use parentheses when accessing it.
Avoid using Count() on arrays unless you include LINQ and understand the difference.
Check for null arrays before accessing Length to prevent errors.