DEV Community

jzfrank
jzfrank

Posted on

C# Initialize a List of Size n

If you want to initialize a list of fixed size n, how should we do this in C#?

First, you should consider just use array. After all, why bother use List if you already know how much elements are there? I mean, you should use List when you don't yet know how many elements are to be...

int[] arr = new int[n];
Enter fullscreen mode Exit fullscreen mode

However, if you insist, here is how:

// most straightforward way 
List<int> L = new List<int> (new int[n]); 
Enter fullscreen mode Exit fullscreen mode

Side remark

Be cautious, new List<int> (n) will give a list of capacity n, instead of a list of length n!

using System;
using System.Collections.Generic; 

public class Program
{
    public static void Main()
    {
        int n = 10;
        List<int> L = new List<int> (n);
        Console.WriteLine("Count = " + L.Count); 
        Console.WriteLine("Capacity = " + L.Capacity); 
    }
}
Enter fullscreen mode Exit fullscreen mode

This gives:

Count = 0
Capacity = 10
Enter fullscreen mode Exit fullscreen mode

Reference

https://stackoverflow.com/questions/466946/how-to-initialize-a-listt-to-a-given-size-as-opposed-to-capacity

Top comments (1)

Collapse
 
hamidto profile image
Hamid Saadi

In certain situations, this approach can be beneficial. When we anticipate that the List will have an initial length and the potential to grow in size, specifying an initial capacity is a practical choice.