• Register
415 points
‚óŹ4

In C# global assembly, the System.Collections.Generic Namespace Contains interfaces and classes that define generic collections, which allow users to create strongly typed collections that provide better type safety and performance than non-generic strongly typed collections.

In System.Collections.Generic Namespace the List<T> Class represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists where 'T' is the type of elements in the list.

How to get size of a list

In class definition, List<T> has a read-only property known as Count. It gets the number of elements contained in the List<T>.

It should be remarked that, Capacity is the number of elements that the List<T> can store before resizing is required. Count is the number of elements that are actually in the List<T>.

Capacity is always greater than or equal to Count. If Count exceeds Capacity while adding elements, the capacity is increased by automatically reallocating the internal array before copying the old elements and adding the new elements.

Retrieving the value of this property is an O(1) operation.

Code Example

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
      List<string> dinosaurs = new List<string>();

      Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);
      Console.WriteLine("Count: {0}", dinosaurs.Count);

      dinosaurs.Add("Tyrannosaurus");
      dinosaurs.Add("Amargasaurus");
      dinosaurs.Add("Mamenchisaurus");
      dinosaurs.Add("Deinonychus");
      dinosaurs.Add("Compsognathus");
      

      Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);
      Console.WriteLine("Count: {0}", dinosaurs.Count);
    }
}