using System;
using System.Collections;
using System.Collections.Generic;
class Program {
// *** before: ***
// a collection stored object, so every element had to be cast back and
// a wrong element was caught only at run time
static int SumOld(ArrayList numbers) {
int total = 0;
foreach (object o in numbers)
total += (int)o; // unboxing on every element
return total;
}
// *** in version 2.0: ***
// List<T> keeps the type of the element, so the compiler checks it
static int SumNew(List<int> numbers) {
int total = 0;
foreach (int n in numbers) // no cast, no boxing
total += n;
return total;
}
// our own methods and classes take type parameters too
static T Largest<T>(T a, T b) where T : IComparable<T> {
return a.CompareTo(b) >= 0 ? a : b;
}
static void Main() {
ArrayList old = new ArrayList();
old.Add(1); old.Add(2); old.Add(3);
old.Add("four"); // compiles, and SumOld breaks on it
Console.WriteLine(old.Count);
List<int> fresh = new List<int>();
fresh.Add(1); fresh.Add(2); fresh.Add(3);
// fresh.Add("four"); // would not compile
Console.WriteLine(SumNew(fresh));
Dictionary<string, int> ages = new Dictionary<string, int>();
ages["Ann"] = 31;
Console.WriteLine(ages["Ann"]);
Console.WriteLine(Largest(6, 7));
}
}