1

I remember in Java once the parent class implements the interface, then all child classes of the parent is now implicitly of type interface (becoming a "super" interface if you will).

public interface IAnimal
{
    // Empty
}


// Parent class
public abstract class Mammal : IAnimal
{
    public string Genus { get; set;}
    
    public string Species { get; set; }
}


public class Dog : Mammal // Dog should be of type IAnimal now?
{
    public string FurColor { get; set; }
}


// Some service class that returns a list of Dog objects
public List<Dog> GetMyDogs()
{
    // Build list using Dog class
}


// Consumer
List<IAnimal> animals = GetMyDogs(); // Throws Cannot implicitly convert type Dog to IAnimal

Is the same capability available in C#?

k_rollo
  • 5,304
  • 16
  • 63
  • 95
  • 2
    `Dog` does implement `IAnimal`, the problem is that it can't implicitly cast `List` to a `List`, see [this](https://stackoverflow.com/q/1817300/9363973) Q&A on how to fix this – MindSwipe May 23 '22 at 05:56
  • A `Dog` is an `IAnimal` but a `List` is not a `List` because `List` is not **covariant**. See [C# variance problem: Assigning List as List](https://stackoverflow.com/q/2033912), which looks to be a duplicate. Agree? – dbc May 23 '22 at 05:57
  • The example does not work in Java either. – luk2302 May 23 '22 at 06:03
  • 1
    @dbc I agree that the variance problem is the underlying cause of the issue, and that the Q&A I linked in my comment is the solution to this issue. In a perfect world we'd close this as a dupe of both – MindSwipe May 23 '22 at 06:07

1 Answers1

1

A Dog is an IAnimal, but a List<Dog> is NOT a List<IAnimal>.

If I could do this:

List<IAnimal> animals = new List<Dog>();

Then I could follow up with this:

animals.Add(new Cat());

But the list is only a list of dogs. Trying to add a cat would be illegal.

Assigning the list only assigns the reference to the list - it doesn't change the list type.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172