Creating variable of type <base class> to store <derived class> object in C#

c#, class, inheritance, object, polymorphism

Solution

The shortest example I can give you is if you want a list of all animals

 List<Animal> Animals = new List<Animal>();
 Animals.Add(new Cat());
 Animals.Add(new Dog());

If you have ever created a project using Winforms, you will have already used something similar since all controls derive from `Control`. You will then notice that a Window has a list of controls (`this.Controls`), that allows you to access all child controls on a window at once. I.E to hide all controls.

 foreach(var control in this.Controls)
      control.Hide();

Problem

I'm somewhat new to programming and I have a question about classes, inheritance, and polymorphism in C#. While learning about these topics, occasionally I'll come across code that looks something like this: ``` Animal fluffy = new Cat(); // where Animal is a superclass of Cat* ``` This confuses me, because I don't understand why someone would create a variable of type Animal to store an object of type Cat. Why wouldn't a person simply write this: ``` Cat fluffy = new Cat(); ``` I do understand why it's legal to store a child object in a parent type variable, but not why it's useful. Is there ever a good reason to store a `Cat` object in an `Animal` variable vs. a `Cat` variable? Can a person give me an example? I'm sure it has something to do with polymorphism and method overriding (and/or method hiding) but I can't seem to wrap my head around it. Thanks in advance!

Original source

Related problems