C# Initialize a List of Size n

jzfrank

jzfrank

Posted on December 19, 2022

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

💖 💪 🙅 🚩
jzfrank
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.

Related

Demystifying Algorithms: Doubly Linked Lists
datastructures Demystifying Algorithms: Doubly Linked Lists

November 29, 2024

Demystifying Algorithms: Circular Linked Lists
datastructures Demystifying Algorithms: Circular Linked Lists

November 29, 2024

Demystifying Algorithms: Singly Linked Lists
datastructures Demystifying Algorithms: Singly Linked Lists

November 29, 2024

i18n e ASP.NET Core Web API
csharp i18n e ASP.NET Core Web API

November 28, 2024