Tuesday, 24 January 2017

POLYMORPHISM IN C# WITH SAMPLE EXAMPLE

Polymorphism is a primary pillars of object oriented programming

Polymorphism allow you to invoke derived class methods through a base class reference during runtime. 

In the base class the method is declared as virtual and in the derived class we override the same method with "override keyword".

The virtual keyword indicates, the method can be overridden in any derived class. 



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

namespace ConsoleApplication4
{

    /// <summary>
    /// Polymorphism example
    /// </summary>
    public class Employee
    {
        public string FirstName = "FN";
        public string LastName = "LN";
     

        public virtual void PrintFullName()
        {
            Console.WriteLine(FirstName + " " + LastName);
        }

    }

    public class FullTimeEmployee : Employee
    {
        public override void PrintFullName()
        {
            Console.WriteLine(FirstName + " " + LastName + "- FullTimeEmployee");
        }
     
    }
    public class PartTimeEmployee : Employee
    {
        public override void PrintFullName()
        {
            Console.WriteLine(FirstName + " " + LastName + " - PartTimeEmployee");
        }
    }
    public class TemporaryEmployee : Employee
    {
        public override void PrintFullName()
        {
            Console.WriteLine(FirstName + " " + LastName + " - TemporaryEmployee");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
           Employee[] employees = new Employee[4];

           employees[0] = new FullTimeEmployee();
           employees[1] = new PartTimeEmployee();
           employees[2] = new TemporaryEmployee();
           employees[3] = new Employee();
           foreach (Employee e in employees)
           {
               e.PrintFullName();
               Console.ReadLine();
           }      

        }

    }
}

No comments:

Post a Comment