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.
- 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.
- using System;
- using System.Collections.Generic;
- namespace ConsoleApp1
- {
- class Program
- {
- static void Main(string[] args)
- {
-
- 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");
-
-
- Console.WriteLine($"Original Capacity: {AuthorList.Capacity}");
-
-
- AuthorList.TrimExcess();
- Console.WriteLine($"Trimmed Capacity: {AuthorList.Capacity}");
-
-
- AuthorList.Capacity = 20;
- Console.WriteLine(AuthorList.Capacity);
- Console.WriteLine($"Updated Capacity: {AuthorList.Capacity}");
- }
- }
- }
The output from above code listing is shown in below figure.