Search code examples
c#abstract-classabstract-factory

Implement abstract factory using generic class and interface


I want to implement an abstract factory (with singletons) and use it in my code with concrete instances of TType and TInterfaceType to be mapped to.

Here is my current code:

public abstract class AbstractFactory<TType, TInterfaceType> where TType : new() where TInterfaceType : class
{
    private TInterfaceType objectTtype;
    public TInterfaceType getInstance()
    {
        try
        {
            if (objectTtype == null)
            {
                objectTtype = new TType();
            }

            return objectTtype;
        }
        catch (Exception e)
        {
            throw e;
        }
    }
}

I get an error:

Cannot implicitly coonvert type TType to TInterfaceType

How can I implement an abstract class with the method definition using a class and its corresponding interface. For example I want to use it as follows:

ConcreteFactory : AbstractFactory<ConcreteClass, IConcreteClass>

Solution

  • You need to add a constraint saying that TType must inherit from TInterfaceType:

    public abstract class AbstractFactory<TType, TInterfaceType> 
                where TType : TInterfaceType, new()
                where TInterfaceType : class
    

    Now the compiler knows that TType inherits from TInterfaceType and objectTtype is therefor assignable (and returnable) to TInterfaceType.