// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; namespace CoGen { public class Program { // **** demo classes and interfaces **** public class P { public void MP() { } } public class C : P { public void MC() { } } public interface IReadonlyContainer { //void Put(T o); // in arg does not match "out" T Get(); } public interface IWriteonlyContainer { void Put(T o); //T Get(); // return value does not match "in" } public class Container : IReadonlyContainer, IWriteonlyContainer { private T o; public void Put(T o) { this.o = o; } public T Get() { return o; } } // **** covariant methods **** public static void TestP_ReadOnly(IReadonlyContainer

co) { //co.Put(new P()); // problem if C or a subclass of C //co.Put(new C()); // problem if a subclass of C P pcopy = co.Get(); pcopy.MP(); //pcopy.MC(); //C ccopy = co.Get(); // problem if P //ccopy.MP(); //ccopy.MC(); } public static void TestC_ReadOnly(IReadonlyContainer co) { //co.Put(new P()); // problem if C or a subclass of C //co.Put(new C()); // problem if a subclass of C P pcopy = co.Get(); pcopy.MP(); //pcopy.MC(); C ccopy = co.Get(); ccopy.MP(); ccopy.MC(); } // **** contravariant methods **** public static void TestP_WriteOnly(IWriteonlyContainer

co) { co.Put(new P()); co.Put(new C()); //P pcopy = co.Get(); // problem if superclass of P //pcopy.MP(); //pcopy.MC(); //C ccopy = co.Get(); // problem if P or a superclass of P //ccopy.MP(); //ccopy.MC(); } public static void TestC_WriteOnly(IWriteonlyContainer co) { //co.Put(new P()); // problem if C co.Put(new C()); //P pcopy = co.Get(); // problem if superclass of P //pcopy.MP(); //pcopy.MC(); //C ccopy = co.Get(); // problem if P or a superclass of P //ccopy.MP(); //ccopy.MC(); } // ***** public static void Main(string[] args) { TestP_ReadOnly(new Container

()); TestP_ReadOnly(new Container()); //TestC_ReadOnly(new Container

()); // P does not match "out C" TestC_ReadOnly(new Container()); TestP_WriteOnly(new Container

()); //TestP_WriteOnly(new Container()); // C does not match "in P" TestC_WriteOnly(new Container

()); TestC_WriteOnly(new Container()); } } }