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];
However, if you insist, here is how:
// most straightforward way
List<int> L = new List<int> (new int[n]);
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);
}
}
This gives:
Count = 0
Capacity = 10
Top comments (1)
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.