Concept of Polymorphism

When you derive a class from a base class, the derived class will inherit all members of the base class except constructors, though whether the derived class would be able to access those members would depend upon the accessibility of those members in the base class
  • 2557

Introduction

When you derive a class from a base class, the derived class will inherit all members of the base class except constructors, though whether the derived class would be able to access those members would depend upon the accessibility of those members in the base class. C# gives us polymorphism through inheritance. Inheritance-based polymorphism allows us to define methods in a base class and override them with derived class implementations.

In object-oriented programming, polymorphism refers to the ability of an entity to refer at run-time to instances of various classes. When a program invokes a method through a super class variable, the correct subclass version of the method is called, based on the type of the reference stored in the super class variable. The same method name and signature can cause different actions to occur, depending on the type of object on which the method is invoked. Facilitates adding new classes to a system with minimal modifications to the system's code. polymorphism enables programmers to deal in generalities and let the execution-time environment handle the specifics. Programmers can command objects to behave in manners appropriate to those objects, without knowing the types of the objects. Polymorphism promotes extensibility: Software that invokes polymorphic behavior is independent of the object types to which messages are sent. New object types that can respond to existing method calls can be incorporated into a system without requiring modification of the base system. Only client code that instantiates new objects must be modified to accommodate new types. This is possible because a subclass object is a super class object as well. When invoking a method from that reference, the type of the actual referenced object, not the type of the reference, determines which method is called. A subclass reference can be aimed at a super class object only if the object is downcast.

Example : Simple example of a polymorphism Consider the following class which we'll use as a base class.

Code

class Animal

{

    public Animal()

    {

        Console.WriteLine("Animal constructor");

    }

    public void Greet()

    {

        Console.WriteLine("Animal says Hello");

    }

    public void Talk()

    {

        Console.WriteLine("Animal talk");

    }

    public virtual void Sing()

    {

        Console.WriteLine("Animal song");

    }

};

 

© 2020 DotNetHeaven. All rights reserved.