// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) // 1. use an enum instead of a string for unit type // 2. use collection instead of array // 3. use decimal instead of double for tax amount // 4. specify the wrong unit type in exception using System; using System.Collections.Generic; namespace E { public enum TypesOfUnit { Car, FactoryInstalled, AfterMarketInstalled } public class Unit { public string Name { get; set; } public TypesOfUnit UnitType { get; set; } public decimal Tax { get; set; } public Unit(string name, TypesOfUnit unittype, decimal tax) { this.Name = name; this.UnitType = unittype; this.Tax = tax; } } public class Program { public static decimal TotalTax(List ulst) { decimal sum = 0; foreach(Unit u in ulst) { sum += u.Tax; } return sum; } public static int NumberOfFactoryInstalled(List ulst) { int sum = 0; foreach(Unit u in ulst) { switch(u.UnitType) { case TypesOfUnit.Car: case TypesOfUnit.AfterMarketInstalled: // nothing break; case TypesOfUnit.FactoryInstalled: sum++; break; default: throw new ArgumentException("Not a valid unit type: " + (int)u.UnitType); } } return sum; } public static void Main(string[] args) { List ulst = new List(); ulst.Add(new Unit("Folkevogn", TypesOfUnit.Car, 240.00m)); ulst.Add(new Unit("Udstyr #1", TypesOfUnit.FactoryInstalled, 10.00m)); ulst.Add(new Unit("Udstyr #2", TypesOfUnit.FactoryInstalled, 50.00m)); ulst.Add(new Unit("Udstyr #3", TypesOfUnit.AfterMarketInstalled, 200.00m)); Console.WriteLine(TotalTax(ulst)); Console.WriteLine(NumberOfFactoryInstalled(ulst)); } } }