0

Just when I thought I had understood inheritance, I get stuck on a problem...

Let's say I've got an abstract class Animal and several derived classes, like this:

public abstract class Animal
{
    public abstract int Age{get;set;}
    public abstract bool Hungry{get;set;}

};

public class Dog:Animal
{
    public bool PottyTrained{get;set;}
}
public class Cat:Animal
{
    public int MiceKilled{get;set;}
}

I now want a method that can handle both Dogs and Cats. I thought I could do it like this:

public List<Animal> FeedAnimals(List<Animal> InAnimals)
{
    foreach(var animal in InAnimals)
    {
        animal.Hungry = false;
    }
    return InAnimals;
}

but when I try it, the compiler tells me "cannot convert from ..." ...

Am I doing something wrong? Is this because I'm passing lists? Any way around it?

Vaethin
  • 316
  • 4
  • 18
  • 5
    `the compiler tells me "cannot convert from ..." ...` What **exactly** did it tell you? – mjwills Apr 19 '18 at 12:53
  • 1
    It would be awesome if you could provide a [mcve]. – mjwills Apr 19 '18 at 12:54
  • Sounds like you don't want the properties to be abstract - only the class. – Hans Kilian Apr 19 '18 at 12:56
  • My guess is that you are trying to pass in a `List` instead of a `List` but with you mysteriously not showing us that code, we can't tell. Also not clear why the two properties are abstract, it makes your code not compile. – DavidG Apr 19 '18 at 12:56
  • What is the exact error? Which line of code gives you the error? – Chetan Apr 19 '18 at 12:57
  • Just because `Dog` is a `Animal` it does not mean that `List` is a `List`. It is not. – Enigmativity Apr 19 '18 at 13:00
  • @mjwills : My VS isn't in English so that won't help you but roughly it's "Type System.Collections.Generic.List can't be converted to GenericList implicitly. – Vaethin Apr 19 '18 at 14:27
  • @Enigmativity Is there any way I can implement whatever kind of Interface VS needs to convert the data from one List Type to another? – Vaethin Apr 19 '18 at 14:28
  • Did you read the duplicate link @Vaethin? – mjwills Apr 19 '18 at 23:04
  • @Vaethin You can do `List animals = listOfDogs.Cast().ToList();`. That makes a copy of your list - but beware that since you've now made a list of animals you can also now add cats to the list. – Enigmativity Apr 20 '18 at 00:03

0 Answers0