-3

List.Capacity does not working

Code

 var xx = new List<int>();    
 xx.Add(1);
 int xxxx = xx.Capacity;// result is 4 and change to 8,12,16 while adding new item to xx list. 

But the capacity is does not working, which mean does not increasing while set the capacity manually

 var xx = new List<int>(1); // or xx.Capacity = 1;   
 xx.Add(1);
 int xxxx = xx.Capacity;// result is always showing 1 does not increasing like 5, 9, 13...
Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234

2 Answers2

0

When you add value in list the capacity also increase automatically if list declared with capacity 1. See in below example when you add first item in list it capacity increased with 4 and then you rich to add fifth item the capacity increase with 4 so the output is 8

The Capacity of the list represents how much memory the list currently has set aside for the current objects and objects to be added to it. The Count of the list is how many items have actually been added to the list. ref: List<> Capacity returns more items than added

    var xx = new List<int>();    
    xx.Add(1);      
    int xxxx = xx.Capacity;
    Console.WriteLine(xxxx); // output : 4
    xx.Add(2);      
    xx.Add(3);      
    xx.Add(4);      
    xx.Add(5);      
    xxxx = xx.Capacity;
    Console.WriteLine(xxxx); // output : 8
Dhaval Asodariya
  • 558
  • 5
  • 19
0

Capacity

Gets or sets the total number of elements the internal data structure can hold without resizing.

The capacity is revaluated in the form on 0 or 2^n and 5 is never an option for that.

var lst = new List<string>(1);            

lst.Add("T1");
lst.Add("T2");
lst.Add("T3");
lst.Add("T4");
lst.Add("T5");

and this is what immediate window said

lst.Count 0 lst.Capacity 1 lst.Count 1 lst.Capacity 1 lst.Count 2 lst.Capacity 2 lst.Count 3 lst.Capacity 4 lst.Count 4 lst.Capacity 4 lst.Count 5 lst.Capacity 8

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208