Geeks With Blogs
Prasanna's Blog BizTalk, WCF, C# and Software Factories

since i have already posted basic ContraVariance in delegate, i am not going to go thru the same again, those of you who had missed my earlier post can refer here

here is an example of using generics with contravariance

namespace ContravarianceWithGenerics
{
    public interface IEquity
    {
        string ToString();
        string Save();
    }

    //base class
    abstract class Equity : IEquity
    {
        int _price;

        public Equity(int Price)
        {
            _price = Price;
        }
        public override string ToString()
        {
            return GetType().Name + " : " + _price;
        }

        #region IEquity Members


        public virtual string Save()
        {
            return "Called from Base Class";
        }

        #endregion
    }
    //derived
    class Stock : Equity
    {
        public Stock(int Price)
            : base(Price)
        {

        }

        public override string Save()
        {
            return "Called from Stock Class";
        }
    }

    //derived
    class Bond : Equity
    {
        public Bond(int Price)
            : base(Price)
        {

        }

        public override string Save()
        {
            return "Called from Bond Class";
        }
    }

    class EquityBusinessImplementation<T> where T: Equity, IEquity
    {
        public delegate void SellNotify(T b);

        public void EquitySaleReport(Equity e)
        {
            Console.WriteLine("Report of sale is " + e);
            Console.WriteLine(e.Save() );
        }
        public SellNotify sellNotifyDlg;

        public void Sell(T s)
        {
            if (null != sellNotifyDlg)
            {
                sellNotifyDlg(s);
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            EquityBusinessImplementation<Stock> s =
                new EquityBusinessImplementation<Stock>();
            s.sellNotifyDlg += s.EquitySaleReport;
            s.Sell(new Stock(100));

            EquityBusinessImplementation<Bond> b =
                new EquityBusinessImplementation<Bond>();
            b.sellNotifyDlg += b.EquitySaleReport;
            b.Sell(new Bond(1000));
        }
    }
}

Happy programming !!!

Posted on Wednesday, March 19, 2008 6:45 PM BizTalk, WCF, Design Patterns, C#, Software Factories , C# , Design Patterns , general | Back to top


Comments on this post: Contravariance and generics

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Prasanna Krishnan | Powered by: GeeksWithBlogs.net