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. // Original Capacity
  17. Console.WriteLine($"Original Capacity: {AuthorList.Capacity}");
  18. // Trim excess
  19. AuthorList.TrimExcess();
  20. Console.WriteLine($"Trimmed Capacity: {AuthorList.Capacity}");
  21. // Update Capacity
  22. AuthorList.Capacity = 20;
  23. Console.WriteLine(AuthorList.Capacity);
  24. Console.WriteLine($"Updated Capacity: {AuthorList.Capacity}");
  25. }
  26. }
  27. }
The output from above code listing is shown in below figure.