vendredi 29 mai 2015

Returning of abstract class creates "cannot convert" exception

Here is a part of factory Method class:

abstract class AbstractProduct
        {
            public int Id { get; set; }
            public AbstractProduct(int id)
            {
                Id = id;
            }
            public AbstractProduct() { }
        }
    class ProductA : AbstractProduct
        {
            public bool SOMETHING { get; set; }
            public ProductA(int id) : base(id)
            {
                SOMETHING = something;
            }
            public ProductA() { }
        }
 abstract class Creator
    {
        public abstract AbstractProduct FactoryMethod(int id,  bool something);
        public abstract AbstractProduct FactoryMethod();
    }

C# samples of this pattern recomend to write something like:

class ProductACreator : Creator
{

    public override AbstractProduct FactoryMethod(int id, bool something)
    {
        return new ProductA(id, something);
    }

}

But i`ve tried to use abstract class for this:

 public override AbstractProduct FactoryMethod(int id, bool something)
        {
            return new ProductA(){ Id = id, SOMETHING = something };
        }

And when I call FactoryMethod from code, my variant of FactoryMethod throw a compiler error on 2nd line:

Creator creator = new ProductACreator();            
AbstractProduct product = creator.FactoryMethod(1, true);

"Cannot convert from 'Program.AbstractProduct' to 'Program.ProductA'"

Please, explain why does it happends and what should I know for not doing this kind of mistakes in future?

Aucun commentaire:

Enregistrer un commentaire