1

I'm trying to understand the Polymorphism, but I cannot understand it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Parent Andrew = new Child();
        }

        class Parent
        {
           public int age;
           public string name;
            public virtual void message()
            {
                Console.WriteLine("I'm a parent");
            }
        }
       
        class Child : Parent
        {
           public string childName;
           public override void message()
           {
                Console.WriteLine("I'm a child");
           }
        }
    }
}

What's the point of creating an instance of "Parent" class and allocating it the pattern of inherited class "Child". I saw this on some tutorials, and I cannot understand why would we do that if we cannot access "Child" class variables through this instance created. Thank you =). Hope I pointed well my problem, if not, let me know.

G Andrei
  • 154
  • 8
  • U can, just have to perform a cast. Imagine u can have a list of parents but in fact "behind" them are all kinds of children with their own properties and logic. In this way you can have a list of object of different types. You can not achieve this without Polymorphism. This is just a small, fast explanation... there are books written to present you the power of Polymorphism. – D A Nov 04 '21 at 13:28
  • Possible duplicate of https://stackoverflow.com/questions/12756048/why-and-when-use-polymorphism – Matthew Watson Nov 04 '21 at 13:30

0 Answers0