safaribook-pro-aspnet-mvc3/chap5_essential_language_fe.../essential_csharp_features/Program.cs

55 lines
1.9 KiB
C#
Raw Normal View History

using System;
2021-07-05 18:21:52 +10:00
using System.Collections.Generic;
using System.Diagnostics;
2021-07-05 18:21:52 +10:00
using automatically_implemented_properties;
namespace automatically_implemented_properties
{
class Program
{
static void Main(string[] args)
{
// create and populate Shopping Cart, implementing IEnumerable<Product> interface
ShoppingCart products = new ShoppingCart
{
2021-07-05 18:21:52 +10:00
Products = new List<Product>
{
new Product {Name = "Kayak", Price = 275M},
new Product {Name = "Lifejacket", Price = 48.95M},
new Product {Name = "Soccer ball", Price = 19.50M},
new Product {Name = "Corner flag", Price = 34.95M}
}
};
// create and populate an array of Product objects, implementing IEnumerable<Product> interface
Product[] productArray =
{
new Product {Name = "Kayak", Price = 275M},
new Product {Name = "Lifejacket", Price = 48.95M},
new Product {Name = "Soccer ball", Price = 19.50M},
new Product {Name = "Corner flag", Price = 34.95M}
};
2021-07-05 18:21:52 +10:00
// get total value of the products in cart
decimal cartTotal = products.TotalPrices();
decimal arrayTotal = productArray.TotalPrices();
2021-07-05 18:21:52 +10:00
Console.WriteLine("Total: {0:c}", cartTotal);
Console.WriteLine("Array Total: {0:c}", arrayTotal);
}
}
2021-07-05 18:21:52 +10:00
public static class MyExtensionMethod
{
public static decimal TotalPrices(this IEnumerable<Product> productEnum)
{
2021-07-05 18:21:52 +10:00
decimal total = 0;
foreach (Product prod in productEnum)
2021-07-05 18:21:52 +10:00
{
total += prod.Price;
}
return total;
}
}
}