Jonas Geiler
Jonas Geiler

Reputation: 193

How does the List class work? (System.Collections.Generic)

An array is defined with a specific size. But if I want a array, which grows dynamically, I use the List class (from namespace System.Collections.Generic). But how does this class work? How does the list grow dynamically?

Upvotes: 0

Views: 40

Answers (1)

Duncan Carr
Duncan Carr

Reputation: 250

using System;
using System.Collections.Generic;

namespace ImmutableLists
{
    class Program
    {
        static void Main()
        {
            List<int> nums = new List<int>(); ;

            for (int i=0; i<=20; i++)
            {
                nums.Add(i);
                Console.WriteLine("{0} : {1}", i, nums.Capacity);
            }

            Console.ReadKey();
        }
    }
}

Lists are immutable - i.e. cannot change in size. How does this work then? They are allocated space, when this is hit, they are dumped, another list is set up with double the previous capacity & the new one is formed. All invisibly of course.

Upvotes: 2

Related Questions