Why cant i access my Milk method.

Joined
Apr 22, 2016
Messages
8
Programming Experience
1-3
I am learning about collections and have made a class that inherits CollectionBase, and uses it to make a list of animals;

I have a second class Cow, and ADD a cow on the Animals list.

Animals has a Feed method.
Cos has a milk method,

When access the list using an indexer, the object is a cow, so why can't I access the milk method?

C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace ConsoleApplication1
{
    public class Animals : CollectionBase
    {
        public void Add(Animal newAnimal)
        {
            List.Add(newAnimal);
        }


        public void Remove(Animal oldAnimal)
        {
            List.Remove(oldAnimal);
        }


        public Animal this[int animalIndex]
        {
            get { return (Animal)List[animalIndex]; }
            set { List[animalIndex] = value; }
        }
    }




    public class Animal
    {
        protected string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }


        public Animal()
        {
            name = "The animal has no name";
        }


        public Animal(string newName)
        {
            name = newName;
        }
        public void Feed() => Console.WriteLine("{0} has been fed", name);
    }


    public class Cow : Animal
    {
        public void Milk() => Console.WriteLine("{0} has been milked", name);
        public Cow(string newName) : base(newName) { }


    }


    class Program
    {
        static void Main(string[] args)
        {
            Animals animalsCollection = new Animals();
            animalsCollection.Add(new Cow("Jane"));


            animalsCollection[0].Feed();
            animalsCollection[0].Milk();




            Console.Read();
        }
    }


}
 
Firstly, don't use CollectionBase. Since the introduction of generics, you should be using the Collection<T> class as a base for your own strongly-typed collection classes. There's actually less work involved in inheriting Collection<T> than there is CollectionBase too.

As for the issue, you're correct that the object is a Cow so you actually can access its Milk method, but the reference is type Animal, so you can only access members of the Animal type via that reference. The indexer for your Animals class is type Animal so if you index an Animals object you will get an Animal reference back. If the actual object is a Cow then you need to cast as type Cow in order to access members of the Cow type. Of course, if you have an Animals collection and you're getting items out of it, you're not likely to know what type of animal each one is, are you? You do in this case but this case is rather contrived.
 
Back
Top Bottom