In depth understanding of C polymorphism

  • 2020-05-17 06:10:36
  • OfStack

MSDN definition above: by inheritance, a class can have multiple types: it can be used as its own type, any base type, or as a type of any interface when implementing the interface.
Polymorphism is explained in two ways
1. At runtime, the object of a derived class can be treated as an object of the base class, with method parameters and locations such as collections or arrays. When this happens, the declared type of the object is no longer the same as the runtime type.
2. Base classes define implementation virtual methods that are overridden by derived classes. At runtime, CLR looks for the runtime type and calls the derived class overridden methods.

    class Shape
    {
        public virtual void Draw()
        {
            Console.WriteLine("Draw a shape");
        }
    }
    class Circle : Shape
    {
        public override void Draw()
        {
            Console.WriteLine("Draw a circle");
        }
    }
    class Rectangle : Shape
    {
        public override void Draw()
        {
            Console.WriteLine("Draw a Rectangle");
        }
    }
    class Triangle : Shape
    {
        public override void Draw()
        {
            Console.WriteLine("Draw a Triangle");
        }
    }
    class Programm
    {
        static void Main()
        {
            // This time, a derived class object can be treated as a base class object 
            Shape[] shapes = 
            {
             new Circle(),
             new Rectangle(),
             new Triangle()
            };

            foreach (Shape s in shapes)
            {
                // call Draw() Method time , A derivation-overridden method is called instead of a base class 
                s.Draw();
            }
        }
    }


Related articles: