I have this code, the question is below the code:
public class MainProgram
{
public static void Main()
{
List<Animal> Animals = new List<Animal>();
Animals.Add(new Dog());
Animals.Add(new Poodle());
Animals.Add(new Poodle());
Animals.Add(new Beagle());
Animals.Add(new Cat());
Bark[] JustTheBarks = Dog.GetBarkList(Animals);
foreach (Bark B in JustTheBarks)
{
Console.WriteLine(B.ToString());
}
}
}
abstract class Animal
{
public abstract Noise GetNoise();
}
class Dog : Animal
{
public override Noise GetNoise()
{
return new Bark("bark");
}
public static Bark[] GetBarkList(List<Animal> List)
{
return List
.OfType<Dog>()
.Select(r => r.GetNoise())
.Cast<Bark>()
.ToArray();
}
}
class Beagle : Dog
{
public override Noise GetNoise()
{
return new Woof("woof", 7);
}
}
class Poodle : Dog
{
public override Noise GetNoise()
{
return new Purr();
}
}
class Cat : Animal
{
public override Noise GetNoise()
{
throw new NotImplementedException();
}
}
class Noise
{
}
class Bark : Noise
{
protected string Text;
public Bark(string Text)
{
this.Text = Text;
}
public override string ToString()
{
return $"{Text}";
}
}
class Woof : Bark
{
protected int Pitch;
public Woof(string Text, int Pitch) : base(Text)
{
this.Pitch = Pitch;
}
public override string ToString()
{
return $"{Text}->{Pitch}";
}
}
class Purr : Noise { }
}
In plain text, Animals and Noises, each animal returns its own type of noise, the noises correspond to the animal class, although sometimes an animal might return different Noises based on some variable (but for a dog only some form of Bark).
This code crashes of course. The Poodle returns a Purr(), and it "should" return something of type Bark. I have the abstract function GetNoise() which just returns a Noise. What I want/need is to write
class Dog
{
public override Bark GetNoise();
}
But this is not allowed, the return type must be the same. I don't want to write a second layer of GetBark() functions in every Dog class, etc.
What I want is to re-write this such that there is no casting, and everything that is derived from Dog is forced to return a Bark in its GetNoise() function such that I can safely write:
Bark B = Dog.GetNoise();