Blog Archive

Friday, August 8, 2014

Covariant and Contravariant

Note that these constraints can be overridden by code, extension method to convert anything to anything

    class Program
    {
        static void Main(string[] args)
        {
            IW<String> iwStr = new W<string>("Test");
            IW<object> iwObj =  iwStr.ToObject2();
        } 
    }

    public interface IW<T>
    {
        T W { get;  }
    }

    public class W<T> : IW<T>
    {
        T _w;
        public W(T w)
        {
            _w = w;
        }
        T IW<T>.W
        {
            get { return _w; }
        }
    }

    public static  class Ext
    {
        public static IW<object> ToObject2(this IW<string> iw)
        {
            return new W<object>(iw.W);
        }
    }

No comments: