C# is an object-oriented programming language, making working with objects a common task. Object lists are fundamental building blocks of programming and are often used to store data, process it, or store the results of operations. In this article, you’ll learn how to create and utilize a list of objects in C#.
Step 1: Creating a Class
Firstly, before creating a list of objects, we need to define our object type. Let’s create a simple “Student” class for this purpose:
1 2 3 4 5 6 7 8 | public class Student { public int StudentID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } |
In the above code snippet, the “Student” class contains three properties, namely, StudentID, FirstName, and LastName, which hold the student’s unique identification, first name, and last name, respectively.
Step 2: Creating the Object List
Now, let’s create an object list of type “Student” and add a few students to it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | using System; using System.Collections.Generic; class Program { static void Main(string[] args) { List<Student> studentList = new List<Student>(); // Adding sample students to the list studentList.Add(new Student { StudentID = 1, FirstName = "John", LastName = "Doe" }); studentList.Add(new Student { StudentID = 2, FirstName = "Jane", LastName = "Smith" }); studentList.Add(new Student { StudentID = 3, FirstName = "Michael", LastName = "Johnson" }); // Printing all students in the list foreach (var student in studentList) { Console.WriteLine($"Student ID: {student.StudentID}, Name: {student.FirstName} {student.LastName}"); } } } |
In the code above, we have created an object list of type “Student” and added three students to it. Subsequently, the information of each student is printed to the console.
In this article, you have learned how to create and use a list of objects in C# programming. Object lists are powerful tools for storing and managing data, and they are commonly used in various programming projects. You can expand and utilize the lists you create as needed. Hopefully, this article has helped you gain a basic understanding of object lists in C#.