// 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) using System; using System.Collections.Generic; namespace E { public class Program { public static string VeryBad(T o) { int len = (int)typeof(T).GetProperty("Count").GetValue(o, null); return (string)typeof(T).GetProperty("Item").GetValue(o, new object[] { (len-1)/2}); } public static T2 PrettyBad(T o) where T : List { int len = (int)typeof(T).GetProperty("Count").GetValue(o, null); return (T2)typeof(T).GetProperty("Item").GetValue(o, new object[] { (len-1)/2}); } public static T2 AlmostThere(T o) where T : List { int len = o.Count; return o[(len-1)/2]; } public static T Better(List o) { int len = o.Count; return o[(len-1)/2]; } public static void Main(string[] args) { List lst = new List(); lst.Add("A"); lst.Add("BB"); lst.Add("CCC"); Console.WriteLine(VeryBad(lst)); Console.WriteLine(PrettyBad,string>(lst)); Console.WriteLine(AlmostThere,string>(lst)); Console.WriteLine(Better(lst)); List lst2 = new List(); lst2.Add(1); lst2.Add(22); lst2.Add(333); // vil smide en fejl // Console.WriteLine(VeryBad(lst2)); Console.WriteLine(PrettyBad,int>(lst2)); Console.WriteLine(AlmostThere,int>(lst2)); Console.WriteLine(Better(lst2)); } } }