- C# Lists Introduction
- C# Lists String Repository
- C# Lists Book Repository
- C# Lists of Class Objects
- C# Lists of Class Objects 2
We are going to move our example along to the next stage after the previous post. Here we are using several techniques in a console program to create a list of Customers and display them to the console. We have a Customer class which is very simple. Next we add another class that holds the list of customers. Thirdly, in the main program, we create the Customer objects, add them to the class that has the list by using a method in that class, and finally we use foreach to iterate through the list to display it on the console. When we display it we are using string interpolation.
In our class we are using properties and primitives. Normally we would just use properties but for illustration we have included primitives.
This C# technique is used in the book called Pro ASP.NET Core MVC, Seventh Edition, by Adam Freeman, published by Apress in 2017. It is under the topic model binding, starting on page 33.
Below is the listing for our class Customer.
namespace ListsOfObjects { class Customer { public int Id = 0; public string Name = ""; public string Status { get; set; } } }
Below is the listing for our Repository class.
using System.Collections.Generic; namespace ListsOfObjects { class Repository { private static List<Customer> privatecustomers = new List<Customer>(); public static IEnumerable<Customer> Customers { get { return privatecustomers; } } public static void AddCustomers(Customer customer) { privatecustomers.Add(customer); } public static int NumberOfCustomers { get { return privatecustomers.Count; } } } }
Below is the listing for our Program.
using System; namespace ListsOfObjects { class Program { static void Main(string[] args) { var cust1 = new Customer { Id = 1, Name = "Joe Smith", Status = "Active" }; var cust2 = new Customer { Id = 1, Name = "Sally Smithers", Status = "Active" }; var cust3 = new Customer { Id = 1, Name = "Third One", Status = "Active" }; Repository.AddCustomers(cust1); Repository.AddCustomers(cust3); foreach (Customer cust in Repository.Customers) { Console.WriteLine($"Name: {cust.Name} Id: {cust.Id} Status: {cust.Status}"); } Console.WriteLine($"Number of customers: {Repository.NumberOfCustomers}"); Console.ReadKey(); } } }