// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; namespace StdGen { public class Program { // **** demo classes **** public class P { public void MP() { } } public class C : P { public void MC() { } } public class Container { private T o; public void Put(T o) { this.o = o; } public T Get() { return o; } } // **** standard generic methods **** public static void Test(Container co, T o) { //co.Put(new P()); // no required relation between T and P //co.Put(new C()); // no required relation between T and C co.Put(o); //P pcopy = co.Get(); // no required relation between T and P //pcopy.MP(); //pcopy.MC(); //C ccopy = co.Get(); // no required relation between T and C //ccopy.MP(); //ccopy.MC(); T tcopy = co.Get(); //tcopy.MP(); //tcopy.MC(); } public static void TestP(Container co, T o) where T : P { //co.Put(new P()); // problem if T is C or a subclass of C //co.Put(new C()); // problem if T is a subclass of C co.Put(o); P pcopy = co.Get(); pcopy.MP(); //pcopy.MC(); //C ccopy = co.Get(); // problem if T is P //ccopy.MP(); //ccopy.MC(); T tcopy = co.Get(); tcopy.MP(); //tcopy.MC(); } public static void TestC(Container co, T o) where T : C { //co.Put(new P()); // problem if T is C or a subclass of C //co.Put(new C()); // problem if T is a subclass of C co.Put(o); P pcopy = co.Get(); pcopy.MP(); //pcopy.MC(); C ccopy = co.Get(); ccopy.MP(); ccopy.MC(); T tcopy = co.Get(); tcopy.MP(); tcopy.MC(); } // **** public static void Main(string[] args) { Test(new Container

(), new P()); Test(new Container(), new C()); TestP(new Container

(), new P()); TestP(new Container(), new C()); //TestC(new Container

(), new P()); // P does not match "T : C" TestC(new Container(), new C()); } } }