C# Initialize a List of Size n
jzfrank
Posted on December 19, 2022
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
Reference
💖 💪 🙅 🚩
jzfrank
Posted on December 19, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.