Polymorphism in C#


HTML clipboard

As we all know C# is a OOP's language. So it implements polymorphism.

C# polymorphism is of two types:

  1. Runtime polymorphism
  2. Compile time polymorphism
We achieve runtime polymorphism by the keyword "override".

There is another keyword which stops the compiler from overriding a particular method by using the Keyword "new" instead of override keyword. The "new" keyword not only stops runtime polymorphism but also allocates a new memory reference for the method with the same signature that of the base class.

Please follow the small example below:

This sample will show the runtime polymorphism:-

The first class defined is:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace ConsoleApplication2
{
    public class Polymorphism
    {
        public virtual void DisplayName()
        {
            Console.WriteLine("This is Runtime polymorphism");
        }
    }
}

The second class defined is:

using System;
using System.Collections.Generic;
using System.Text;
using ConsoleApplication2;
using System.IO;

namespace ConsoleApplication2
{
    class Polymorphism1 :Polymorphism
    {
        public override void DisplayName()
        {
            Console.WriteLine("This is  not Runtime polymorphism");
        }
    }
}

The main class defined is:

using System;
using System.Collections.Generic;
using System.Text;
using ConsoleApplication2;
using System.IO;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Polymorphism1 obj = new Polymorphism1();
            obj.DisplayName();
            Console.ReadKey();

        }
    }
}


This is the next sample which will show us how to stop runtime polymorphism:-

The first class defined is:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace ConsoleApplication2
{
    public class Polymorphism
    {
        public virtual void DisplayName()
        {
            Console.WriteLine("This is Runtime polymorphism");
        }
    }
}

The second class defined is:

using System;
using System.Collections.Generic;
using System.Text;
using ConsoleApplication2;
using System.IO;

namespace ConsoleApplication2
{
    class Polymorphism1 :Polymorphism
    {
        public new void DisplayName()
        {
            Console.WriteLine("This is  not Runtime polymorphism");
        }
    }
}

The main class defined is:

using System;
using System.Collections.Generic;
using System.Text;
using ConsoleApplication2;
using System.IO;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Polymorphism1 obj = new Polymorphism1();
            obj.DisplayName();
            Console.ReadKey();

        }
    }
}









 

erver'>

Similar Articles