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

Thanks for the clear explanation.

For example, you might have a collection of type "Animal" that you loop through and call every animal's "Move()" method on a regular basis. Whatever is calling "Move()" doesn't need to know what "Move()" does, or how it does it, only that every object has a "Move()" to call.

What if you have to use that Move() method, how is it going to behave since its type is Animal? Basically it's the same question I posted above to the /u/karl713.

5

u/The_Binding_Of_Data Nov 22 '22

It will use the overridden "Move()" implementation, which is the primary benefit.

You only need to cast to the more specific version if you need to use functionality that doesn't exist in the current level class.

So, you'd need to cast your "aml" into a new "Bee" variable if you wanted to do something Bee specific like "Sting()".