In your example, there really isn't an advantage. A more typical scenario which would emphasize the power of polymorphism is the following:
public class Foo
{
public Animal GetAnimal()
{
return new Dog();
}
}
public class Bar
{
public void DoSomething()
{
Foo foo = new Foo();
Animal animal = foo.GetAnimal();
}
}
So, why not just return a Dog
in the method instead of an animal? Because good coding practices tell us to return the least derived class that would be sufficient enough in providing access to the members. An even more likely scenario would be to return an interface instead:
public class Foo
{
public IAnimal GetAnimal()
{
return new Dog();
}
}
In a real-world scenario, the most often case I've run across is a method which returns IEnumerable<T>
, but really returns an array. Why not just return the array? Because the consumer only needs a sequence of elements, not the underlying data structure.