How To Create A List Of Objects In C#?

A list is a collection of items that can be accessed by index and provides functionality to search sort, and manipulate list items.

The List<T> class is defined in the System.Collections.Generic namespace is a generic class and can store any data type to create a list. Before you use the List class in your code, you must import the System.Collections.Generic namespace using the following line. 

using System.Collections.Generic;

Let's create a class and some objects and then create a list of objects in C#.

We have a class named Author that has five pubic properties Name, Age, BookTitle, IsMVP, and PublishedDate of type string, short, string, bool, and DateTime, respectively.

public class Author
{
    private string name;
    private short age;
    private string title;
    private bool mvp;
    private DateTime pubdate;
  
    public Author(string name, short age, string title, bool mvp, DateTime pubdate)
    {
        this.name = name;
        this.age = age;
        this.title = title;
        this.mvp = mvp;
        this.pubdate = pubdate;
    }
  
    public string Name
    {
        get { return name;  }
        set { name = value; }
    }
  
    public short Age
    {
        get { return age; }
        set { age = value; }
    }
    public string BookTitle
    {
        get { return title; }
        set { title = value; }
    }
    public bool IsMVP
    {
        get { return mvp; }
        set { mvp = value; }
    }
    public DateTime PublishedDate
    {
        get { return pubdate; }
        set { pubdate = value; }
    }
}

The following code snippet creates a List of Author types.

List<Author> AuthorList = new List<Author>();

The following code snippet creates the Author objects and adds them to the List.

AuthorList.Add(new Author("Mahesh Chand", 35, "A Prorammer's Guide to ADO.NET", true, new DateTime(2003,7,10)));
AuthorList.Add(new Author("Neel Beniwal", 18, "Graphics Development with C#", false, new DateTime(2010, 2, 22)));
AuthorList.Add(new Author("Praveen Kumar", 28, "Mastering WCF", true, new DateTime(2012, 01, 01)));
AuthorList.Add(new Author("Mahesh Chand", 35, "Graphics Programming with GDI+", true, new DateTime(2008, 01, 20)));
AuthorList.Add(new Author("Raj Kumar", 30, "Building Creative Systems", false, new DateTime(2011, 6, 3)));

The following code snippets loop through the List and print out all the items on the List.

foreach (var author in AuthorList)
{
    Console.WriteLine("Author: {0},{1},{2},{3},{4}", author.Name, author.Age, author.BookTitle, author.IsMVP, author.PublishedDate);
}

Here is a detailed article on C# List.

C# List Tutorial - Everything You Need To Learn About List In C# (c-sharpcorner.com)

 

 


Similar Articles
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.