I am building a code generator which will generate code that follows interfaces which inherit an underlying interface. I thought that I could use a generic class for this, but I think I have hit the Covariant / Contravariant problem, and trying to work out the best solution to this. I cannot tell if I can use to solve this, or if I just have to avoid generics for this.

I can boil what I am trying to do down to the following example:

    public interface Animal
    {
        string Name { get; }
    }

    public class Dog : Animal
    {
        public string Name { get; set; }
        public bool WalksEveryDay { get; set; }
    }
    public class Snake : Animal
    {
        public string Name { get; set; }
        public bool GoesForSlitherEveryDay { get; set; }
    }

    public class AnimalInterfaceFactory<T> where T : Animal
    {
        public T GetNew(int animaltype)
        {
            switch(animaltype)
            {
                case 0: return new Dog();   // Compile Error - Cannot Implicitly convert type Dog to T'
                case 1: return new Snake(); // Compile Error - Cannot Implicitly convert type Dog to T'
                    // (also needs default)
            }   
        }
    }

I was hoping to avoid doing the following each of the possible interfaces, as I will have to repeat the same code for every type the code generation needs to support.

    public class DogFactory
    {
        public Animal GetNew()
        {
            return new Dog();  // This works, because Dog inherits Dog, and this factory wont be used for snakes.
        }
    }
1

There are 1 best solutions below

0
Zen Of Kursat On

try the "out" keyword

public class AnimalInterfaceFactory<out T> where T : Animal

and casting like this may what you need:

...

case 0: return (T)(object)new Dog();
case 1: return (T)(object)new Snake();
...