How To Get And Set Size Of A C# List

C# List<T> class provides methods and properties to create a list of objects (classes).
 
List is a generic class. You must import the following namespace before using the List<T> class.
  1. using System.Collections.Generic;
List.Capacity
 
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.
  1. using System;  
  2. using System.Collections.Generic;  
  3. namespace ConsoleApp1  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             // Create a list of strings  
  10.             List<string> AuthorList = new List<string>();  
  11.             AuthorList.Add("Mahesh Chand");  
  12.             AuthorList.Add("Praveen Kumar");  
  13.             AuthorList.Add("Raj Kumar");  
  14.             AuthorList.Add("Nipun Tomar");  
  15.             AuthorList.Add("Dinesh Beniwal");  
  16.   
  17.             // Original Capacity  
  18.             Console.WriteLine($"Original Capacity: {AuthorList.Capacity}");  
  19.   
  20.             // Trim excess  
  21.             AuthorList.TrimExcess();  
  22.             Console.WriteLine($"Trimmed Capacity: {AuthorList.Capacity}");  
  23.   
  24.             // Update Capacity  
  25.             AuthorList.Capacity = 20;  
  26.             Console.WriteLine(AuthorList.Capacity);  
  27.             Console.WriteLine($"Updated Capacity: {AuthorList.Capacity}");  
  28.         }  
  29.     }  
  30. }  
The output from above code listing is shown in below figure.
 
 
 



Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.