Reader Level:

How to get and set size of a C# List

By Mahesh Chand on Jul 05, 2012
How to get and set size of a List using C#.


The Capacity property gets and sets the number of items a list can hold without resizing. Capacity is always greater than or equal to the Count value. 

The following code snippet creates a List of authors and displays the original capacity. After that, code removes the excess capacity by calling TrimExcess method. After that, capacity is set to 20. 

// Create a list of strings
List<string> AuthorList = new List<string>();
AuthorList.Add("Mahesh Chand");
AuthorList.Add("Praveen Kumar");
AuthorList.Add("Raj Kumar");
AuthorList.Add("Nipun Tomar");
AuthorList.Add("Dinesh Beniwal");

// Original Capacity
Console.WriteLine("Original Capacity: {0}", AuthorList.Capacity);
// Trim excess 
Console.WriteLine("Trimmed Capacity: {0}", AuthorList.Capacity);
// Update Capacity
AuthorList.Capacity = 20;
Console.WriteLine("Updated Capacity: {0}", AuthorList.Capacity);

Download Free book: Programming List with C#

Mahesh Chand
Mahesh Chand

C# Corner founder, 10-times Microsoft MVP, technical author, and software architect. Mahesh authored his first book, A Programmer’s Guide to ADO.NET in C# with APress at the age of 25. C# Corner is a memb... Read more



Spire.Doc - Free .NET Word API
Use Spire.Doc to create, read, write, print, and convert word documents to OpenXML, RTF, TXT, XPS, EPUB, EMF, HTML, Image and PDF.

Trending up

Infragistics jQuery Controls