0

I have written a simple excample to clearify my Problem. This is the Code:

internal interface IAnimal
{
    string Name { get; set; }
}

class Animal : IAnimal
{
    public string Name { get; set; }
}

class Cow : Animal {}
class Sheep : Animal {}


internal interface IFarm<T> where T : IAnimal
{
    T TheAnimal { get; }
}

class Farm<T> : IFarm<T> where T : IAnimal
{
    public T TheAnimal { get; }
}


class CattleFarm : Farm<Cow> {}
class SheepFarm : Farm<Sheep> {}


class Demo
{
    private IFarm<IAnimal> AnyFarm;
    void Foo()
    {
        AnyFarm = new CattleFarm();
        var name = AnyFarm.TheAnimal.Name;
        AnyFarm = new SheepFarm();
        name = AnyFarm.TheAnimal.Name;
    }
}

Why do I get the compiler error when trying to assign CattleFarm or SheepFarm to AnyFarm?

Where is my fault?

Wernfried
  • 206
  • 3
  • 9
  • `AnyFarm` is of type `IFarm` where `CattleFarm` is of type `Farm` and `SheepFarm` is of type `Farm`. Inheritance does not authorize casting. – Hank Nov 15 '16 at 15:16
  • Shouldn't it be "CattleFarm AnyFarm = New CattleFarm()"?? – Tyron78 Nov 15 '16 at 15:16
  • @AlfieGoodacre No, it *is* actually of type `Farm`. That's what inheritance means. It's not of type `IFarm`. – Servy Nov 15 '16 at 15:17

0 Answers0