Task 2 – Using Extension Methods with Generic Types
Extension methods can be added to any type, including the generic types such as List<T> and Dictionary<K, V>. 1. Add an extension method, Append,to the Extensions class that combines all elements of two List<T> objects into a single List<T>: public static class Extensions { public static List<T> Append<T>(this List<T> a, List<T> b) { var newList = new List<T>(a); newList.AddRange(b); return newList; } public static bool Compare(this Customer customer1, Customer customer2) { …
2. return to the Main methodand use the Append method to append the addedCustomers list to the customers list. Check this new list to see if the newCustomer is in the updated list: static void Main(string[] args) { var customers = CreateCustomers();
var addedCustomers = new List<Customer> { new Customer(9) { Name = "Paolo Accorti", City = "Torino" }, new Customer(10) { Name = "Diego Roel", City = "Madrid" } };
var updatedCustomers = customers.Append(addedCustomers);
var newCustomer = new Customer(10) { Name = "Diego Roel", City = "Madrid" }; foreach (var c in updatedCustomers) { …
3. Press Ctrl+F5 to build and run the application, which now displays “The new customer was already in the list”. Press any key to terminate the application.
Extension methods provide an elegant way to extend types with functionality you develop, making the extensions appear to be part of the original types. Extension methods enable new functionality to be added to an already compiled class. This includes user created classes as well as.NET classes such as List<T>.
|