C# List Length – How to get (and set) the Length of a List in C#

Introduction

On the face of it, this is a really easy one: just use List.Count:

Simple Example of getting List Length using List.Count in C#

var numbers = new List<int> {1, 2, 3};	
Console.WriteLine(numbers.Count);

/* this code outputs:
3
*/

Length Vs Count in C#

It’s common to use Arrays before using Lists (at least if you’re as old as I am!) so it often feels natural to use Length. That said, Length is not very widely available – it’s usually seen on Arrays and Strings:

var numbers = new int[] {1, 2, 3};
Console.WriteLine($"array length: {numbers.Length}");
	  
var myString = "some string";
Console.WriteLine($"string length: {myString.Length}");

/* this code outputs:
array length: 3
string length: 11
*/

List Count vs Capacity

List.Count will tell you how many items there are in your list, while List.Capacity gets (and sets) the number of items the list can hold without resizing.

For as a background, it’s worth reminding ourselves that Lists (unlike arrays) will resize dynamically – that is you can keep adding items to a list and it will grow to allow the items to fit. Capacity is added in chunks (powers of 2), so that resizing happens occasionally (not every time an element is added):

using System;
using System.Collections.Generic;
					
var numbers = new List<int>();	
Console.WriteLine($"Count: {numbers.Count}");
Console.WriteLine($"Capacity: {numbers.Capacity}");
var prevCapacity = numbers.Capacity;
var loop = 0;
while (loop <= 8)
{
	numbers.Add(1);
	if (numbers.Capacity != prevCapacity)
	{
		prevCapacity = numbers.Capacity;
		loop++;
		Console.WriteLine($"Capacity: {numbers.Capacity}");
	}
}

/* this code outputs:
Count: 0
Capacity: 0
Capacity: 4
Capacity: 8
Capacity: 16
Capacity: 32
Capacity: 64
Capacity: 128
Capacity: 256
Capacity: 512
Capacity: 1024
*/

Setting the capacity of an array in C#

It’s also possible to control the capacity of a List manually, either when the List is initialised (as in this example where we set the capacity to 10):

var numbers = new List<int>(10) {1, 2, 3};	
Console.WriteLine($"Count: {numbers.Count}");
Console.WriteLine($"Capacity: {numbers.Capacity}");

/* this code outputs:
Count: 3
Capacity: 10
*/

Or after initialisation, as in this example where we set it to 20:

var numbers = new List<int> {1, 2, 3};	
Console.WriteLine($"Count: {numbers.Count}");
numbers.Capacity = 20;
Console.WriteLine($"Capacity: {numbers.Capacity}");

/* this code outputs:
Count: 3
Capacity: 20
*/

When setting the capacity, it might be tempting to set it to a value smaller than the list’s current size. Don’t do it – this will result in an exception being thrown at runtime:

using System.Collections.Generic;
					
var numbers = new List<int> {1, 2, 3};	
numbers.Capacity = 2;

/* this code outputs:
Unhandled exception. System.ArgumentOutOfRangeException: capacity was less than the current size. (Parameter 'value')
   at System.Collections.Generic.List`1.set_Capacity(Int32 value)
   at <Program>$.<Main>$(String[] args)
Command terminated by signal 6
*/

ICollection Count property

List isn’t the only datatype in C# to have a Count property, in fact every type that implements the ICollection interface has a count property, some notable examples include: Dictionary, HashSet and SortedSet. A more complete list is available in the ICollection docs.

IEnumerable Count() method

There is another, more generic (implemented by more diverse objects) option – that’s to use the Linq IEnumerable.Count() method:

using System;
using System.Linq;

public class Program
{
  public static void Main()
  {
    var numbers = new int[] {1, 2, 3};
    Console.WriteLine($"array length: {numbers.Count()}");
  }
}

/* this code outputs:
array length: 3
*/

Note the line at the top saying “using System.Linq” – you’ll get an error if you don’t include that.

This method is more widely available than either the Length or Count properties, but it can be much slower. For more in depth discussion on Count vs Count() you can see my post on the subject: C# Linq Count

Leave a Reply

Your email address will not be published. Required fields are marked *