c sharp

System Collection Generic List C#

System Collections Generic List is a powerful and versatile data structure in C# that allows storing a collection of elements of the same type. This article will explain what System.Collections.Generic List is, how to use it, and provide a code example to illustrate its use.

What is System Collections Generic List in C#

System Collections Generic List is a class that is part of the System Collections generic namespace in C#. It is used to store a collection of elements of the same type. The elements are stored in a  memory location, which makes it easy to access and manipulate the elements in the list. You can add, remove, and access elements from the list using index-based access.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Create a new List of integers
        List<int> myList = new List<int>();
        // Add elements to the List
        myList.Add(1);
        myList.Add(2);
        myList.Add(3);
        // Access elements using index-based access
        int firstElement = myList[0];
        int secondElement = myList[1];
        int thirdElement = myList[2];
        // Print the elements
        Console.WriteLine("First Element: " + firstElement);
        Console.WriteLine("Second Element: " + secondElement);
        Console.WriteLine("Third Element: " + thirdElement);
    }
}

 

In the above code, we create a new List of integers, add three elements to the list, and then access the elements using index-based access. Finally, we print the elements to the console and here is the output for this code:

There are many other methods that you can use with the List class, such as inserting elements, removing elements, sorting elements, and much more. The List class provides a rich set of methods that make it easy to manipulate collections of elements.

Conclusion

System collections generic list is a versatile and powerful data structure in C# that is commonly used to store collections of elements of the same type. It provides an efficient way to store and manipulate elements using index-based access and this article provides an example of how to use the List class in C# and highlighted some of its features. If you need to store a collection of elements of the same type, then System collections generic list is an excellent choice.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.