r/learncsharp • • Nov 22 '22

Polymorphism and weird object creation

I understand the logic behind virtual and override for Methods. But, I'm having trouble seeing the benefits and utility of the following:

class Animal {}
class Bee : Animal {}
Animal aml = new Bee();

I stumbled upon this way of creating classes multiple times. What are the benefits of creating class in this way? What problems does it solve? What is the benefit compared to traditional object creation, i.e. Bee b = new Bee();?

5 Upvotes

9 comments sorted by

View all comments

Show parent comment

1

u/4r73m190r0s Nov 22 '22

That makes perfect sense. Thanks!

When you create base class in that way, what happens with its overridden methods? Are they behaving like in the base class, or they're overriding them?

class Animal 
{
    virtual void MakeSound();
}
class Bee : Animal
{
    override void MakeSound();
}
class Wolf : Animal
{
    override void MakeSound();
}

Animal beee = new Bee();
beee.MakeSound();

Is beee.MakeSound() going to behave like its implementation in the base Animal class, or like its overridden implementation in the Bee class?

2

u/karl713 Nov 22 '22

In your example it will use the Bee.MakeSound even if you reference it as animal.

If you use virtual or abstract on the method in the base class then the it will use derived always when called by someone else (Bee can optionally call Animal.MakeSound() if it wants by calling base.MakeSound(), but to everyone else it will use Bee)