- Use an extension method to add functionality to a class you wouldn't normally have access to.
We're going to extend List to check for in stock items. This is a check that we would potentially do a lot in the future of our program. So adding a method to do this will make the code more readable and easier to maintain.
- Create a new
staticclass. Call itListExtensions. - In this class we're going to create a static method. This one will be kind of complicated, so here's the method signature:
public static List<T> InStock<T>(this List<T> list) where T: Product. - Your mentors should have explained a little bit about generics. They're not critical to understanding extension methods, but hopefully it will take some of the mystery out of how the method is working. You'll learn much more about generics in the next course.
- In the method body, return the "in stock" code we wrote last time. Since this method is returning a list, remember to add the
ToListat the end. - We can now use this new method in our
ProductLogicclass. Go replace the "in stock" logic with this new method. - Add a new method (don't forget the interface) called
GetTotalPriceOfInventory. It will return a decimal. Use your newInStockmethod, theSelectmethod, and theSummethod to get your result. - Add a new UI option for the new method.
- Now just test to make sure it works correctly.