Richard Brennan
Member
- 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?
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();
}
}
}