Sunday, September 25, 2011

Polymorphism In C#


Polymorphism In C# With Examples


Polymorphism is an important and fundamental pillar of Object Oriented Programming.Polymorphism means many forms . Polymorphism is of two types.
1. Compile Time Polymorphism/Method Overloading
2.Runtime Polymorphism/Method Overriding.

Compile Time Polymorphism
Compile time polymorphism is done within a class having two methods with the same name but should have two different parameters
Runtime Polymorphism
Runtime Polymorphism is implemented when we create a base class with virtual methods and create derived classes that overide the behavior ofthe base class's virtual method

Method Overloading Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
   class Mymath
    {
        public int Add(int a,int b)
        {
            return a + b;
        }
        public int Add(int a, int b, int c)
        {
           return a + b + c;
       }
    }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// Default Program Class
    class Program
    {
        static void Main(string[] args)
        {
            Mymath obj = new Mymath();
            obj.Add();
            Console.ReadLine();

        }
    }

Method Overiding Example
Examples From Three Classes
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// Derived Class  
class Cat:Pet
    {
        public override void faithful()
        {
            Console.WriteLine("I am faithful");       
        }
    }
//Base Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

  class Pet
    {
        public virtual void faithful()
        {
            Console.WriteLine("I am faithful");

        }
    }

//Default Program Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

    class Program
    {
        static void Main(string[] args)
        {
            Cat obj = new Cat();
            obj.faithful();
            Console.ReadLine();
        }
    }