marc3l
marc3l

Reputation: 2595

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>

Upvotes: 4

Views: 66

Answers (1)

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43886

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.

Upvotes: 3

Related Questions