Thursday 5 December 2013

What is polymorphism and types of polymorphism in C#.NET?


In this article I will explain what is polymorphism and types of polymorphism in C#.NET.

Polymorphism means same operation may behave differently on different classes.
An operation may exhibit different behaviours in different instances.
The behaviour depends on the data types used in the operation.
Polymorphism is extensively used in implementing Inheritance.

 In Polymorphism we have 2 different types those are

       -  Overloading
       -  Overriding


 Overloading

Overloading means we will declare methods with same name but different signatures because of this we will perform different tasks with same method name. This overloading also called as compile time polymorphism or early binding.

Example of Method Overloading:

      class A1
        {
            void hello()
            {
                Console.WriteLine("Hello");
            }

            void hello(string s)
            {
                Console.WriteLine("Hello {0}", s);
            }
        }

Overriding

Overriding also called as run time polymorphism or late binding or dynamic polymorphism. Method overriding or run time polymorphism means same method names with same signatures.

Example of Method Overriding:

        class parent
        {
            virtual void hello()
            {
                Console.WriteLine("Hello from Parent");
            }
        }

        class child : parent
        {
            override void hello()
            {
                Console.WriteLine("Hello from Child");
            }
        }

        static void main()
        {
            parent objParent = new child();
            objParent.hello();
        }

No comments:

Post a Comment