Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / C#

Polymorphism in .NET

Rate me:
Please Sign up or sign in to vote.
4.93/5 (92 votes)
4 Jun 2013CPOL7 min read 382.8K   1   99   43
This post discusses polymorphism in .NET

Introduction

In this post, you will learn the following topics:

  1. Polymorphism
  2. Static or compile time polymorphism
    • Method overloading
  3. Dynamic or runtime polymorphism
    • Method overriding
  4. Virtual keyword and virtual method
  5. Difference between method overriding and method hiding
  6. Sealed method

What is Polymorphism?

Polymorphism means one name many forms. Polymorphism means one object behaving as multiple forms. One function behaves in different forms. In other words, "Many forms of a single object is called Polymorphism."

Real World Example of Polymorphism

Example 1

  • A Teacher behaves with student.
  • A Teacher behaves with his/her seniors.

Here teacher is an object but the attitude is different in different situations.

Example 2

  • Person behaves as a SON in house, at the same time that person behaves like an EMPLOYEE in the office.

Example 3

Your mobile phone, one name but many forms:

  • As phone
  • As camera
  • As mp3 player
  • As radio

With polymorphism, the same method or property can perform different actions depending on the run-time type of the instance that invokes it.

There are two types of polymorphism:

  1. Static or compile time polymorphism
  2. Dynamic or runtime polymorphism

Static or Compile Time Polymorphism

In static polymorphism, the decision is made at compile time.

  • Which method is to be called is decided at compile-time only.
  • Method overloading is an example of this.
  • Compile time polymorphism is method overloading, where the compiler knows which overloaded method it is going to call.

Method overloading is a concept where a class can have more than one method with the same name and different parameters.

Compiler checks the type and number of parameters passed on to the method and decides which method to call at compile time and it will give an error if there are no methods that match the method signature of the method that is called at compile time.

Example

C#
namespace MethodOverloadingByManishAgrahari
{
    class Program
    {
        public class TestOverloading
        {

            public void Add(string a1, string a2)
            {
                Console.WriteLine("Adding Two String :" + a1 + a2);
            }

            public void Add(int a1, int a2)
            {
                Console.WriteLine("Adding Two Integer :" +  a1 + a2);
            }

        }

        static void Main(string[] args)
        {
            TestOverloading obj = new TestOverloading();

            obj.Add("Manish " , "Agrahari");

            obj.Add(5, 10);

            Console.ReadLine();
        }
    }
}

Dynamic or Runtime Polymorphism

Run-time polymorphism is achieved by method overriding.

Method overriding allows us to have methods in the base and derived classes with the same name and the same parameters.

By runtime polymorphism, we can point to any derived class from the object of the base class at runtime that shows the ability of runtime binding.

Through the reference variable of a base class, the determination of the method to be called is based on the object being referred to by reference variable.

Compiler would not be aware whether the method is available for overriding the functionality or not. So compiler would not give any error at compile time. At runtime, it will be decided which method to call and if there is no method at runtime, it will give an error.

See the following example:

C#
namespace PolymorphismByManishAgrahari
{
    class Program
    {
        public class Base
        {

            public virtual void Show()
            {
                Console.WriteLine("Show From Base Class.");
            }
        }

        public class Derived : Base
        {
            public override void Show()
            {
                Console.WriteLine("Show From Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBase;
            objBase = new Base();
            objBase.Show();//    Output ----> Show From Base Class.

            objBase = new Derived();
            objBase.Show();//Output--> Show From Derived Class.

            Console.ReadLine();
        }
    }
} 

Compiler demands virtual Show() method and it compiles successfully. The right version of Show() method cannot be determined until run-time since only at that time Base objBase is initialized as Derived.

Virtual Keyword

According to MSDN, “The virtual keyword is used to modify a method, property, indexer or event declaration, and allow it to be overridden in a derived class.”

Virtual Method

Virtual method is a method whose behavior can be overridden in derived class. Virtual method allows declare a method in base class that can be redefined in each derived class.

When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.

  • By default, methods are non-virtual. You cannot override a non-virtual method.
  • You cannot use the virtual modifier with the static, abstract, private or override modifiers.
  • Virtual properties behave like abstract methods, except for the differences in declaration and invocation syntax.
  • It is an error to use the virtual modifier on a static property.
  • A virtual inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.

Virtual method solves the following problem:

In OOP, when a derived class inherits from a base class, an object of the derived class may be referred to (or cast) as either being the base class type or the derived class type. If there are base class methods overridden by the derived class, the method call behavior is ambiguous.

In C#, polymorphism is explicit - you must have a virtual (or abstract) modifier on the base class method (member) and an override on the derived class method, which you probably already know.

If you don't put a modifier on a base class method, polymorphism can't ever happen. If you then add a non-modified method to the derived class with the same signature as the non-modified base class method, the compiler will generate a Warning message.

See the following example:

C#
namespace PolymorphismByManishAgrahari
{
    class Program
    {
        public class Base
        {

            public void Show()
            {
                Console.WriteLine("Show From Base Class.");
            }
        }

        public class Derived : Base
        {
            //Following line will Give an Warning
            /*
             'PolymorphismByManishAgrahari.Program.Derived.Show()'
  hides  inherited member
             'PolymorphismByManishAgrahari.Program.Base.Show()'.
              Use the new keyword if hiding was intended.
            */
            public void Show()
            {
                Console.WriteLine("Show From Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBase = new Base();
            objBase.Show();//    Output ----> Show From Base Class.

            Derived objDerived = new Derived();
            objDerived.Show();//Output--> Show From Derived Class.


            Base objBaseRefToDerived = new Derived();
            objBaseRefToDerived.Show();//Output--> Show From Base Class.

            Console.ReadLine();
        }
    }
}

It means that you are hiding (re-defining) the base class method.

In other languages, take Java for instance, you have what is called "implicit" polymorphism where just putting the method in the derived class with the same signature as a base class method will enable polymorphism.

In Java, all methods of a class are virtual by default unless the developer decides to use the final keyword thus preventing subclasses from overriding that method. In contrast, C# adopts the strategy used by C++ where the developer has to use the virtual keyword for subclasses to override the method. Thus all methods in C# are non virtual by default.

The C# approach is more explicit for the purpose of making the code safer in versioning scenarios, i.e., you build your code based on a 3rd party library and use meaningful, but common, method names. The 3rd party library upgrades, using the same common method name. With implicit polymorphism the code would break, but with C#, you would receive a compiler warning so you can double check to see if polymorphism was something you wanted to do.

Difference between Method Overriding and Method Hiding

Method overriding allows a subclass to provide a specific implementation of a method that is already provided by base class. The implementation in the subclass overrides (replaces) the implementation in the base class.

The important thing to remember about overriding is that the method that is doing the overriding is related to the method in the base class.

When a virtual method is called on a reference, the actual type of the object to which the reference refers is used to determine which method implementation should be used. When a method of a base class is overridden in a derived class (subclass), the version defined in the derived class is used. This is so even should the calling application be unaware that the object is an instance of the derived class.

C#
namespace PolymorphismByManishAgrahari
{
    class Program
    {
        public class Base
        {

            public virtual void Show()
            {
                Console.WriteLine("Show From Base Class.");
            }
        }

        public class Derived : Base
        {
//the keyword "override" change the base class method.
            public override void Show()
            {
                Console.WriteLine("Show From Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBaseRefToDerived  = new Derived();
            objBaseRefToDerived .Show();//Output--> Show From Derived Class.

            Console.ReadLine();
        }
    }
}

Output--> Show From Derived Class

Method hiding does not have a relationship between the methods in the base class and derived class. The method in the derived class hides the method in the base class.

C#
namespace PolymorphismByManishAgrahari
{
    class Program
    {
        public class Base
        {

            public virtual void Show()
            {
                Console.WriteLine("Show From Base Class.");
            }
        }

        public class Derived : Base
        {

            public new void Show()
            {
                Console.WriteLine("Show From Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBaseRefToDerived  = new Derived();
            objBaseRefToDerived .Show();//Output--> Show From Base Class.

            Console.ReadLine();
        }
    }
}

Output is:? Show From Base Class.

In the preceding example, Derived.Show will be called; because, it overrides Base.Show.

The C# language specification states that "You cannot override a non-virtual method." See the following example:

C#
namespace PolymorphismByManishAgrahari
{
    class Program
    {
        public class Base
        {

            public void Show()
            {
                Console.WriteLine("This is Base Class.");
            }
        }

        public class Derived : Base
        {
            //Following Line will give error.
            /*
             Error:- 'PolymorphismByManishAgrahari.Program.Derived.Show()'
cannot override inherited member  'PolymorphismByManishAgrahari.Program.Base.Show()'
             * because it is not marked virtual, abstract, or override
             */
            public override void Show()
            {

                Console.WriteLine("This is Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBase = new Base();
            objBase.Show();//    Output ----> This is Base Class.

            Derived objDerived = new Derived();
            objDerived.Show();//Output--> This is Derived Class.

            Base objBaseRefToDerived = new Derived();
            objBaseRefToDerived.Show();//Output--> This is Base Class.

            Console.ReadLine();
        }
    }
}

Error: 'PolymorphismByManishAgrahari.Program.Derived.Show()' cannot override inherited member 'PolymorphismByManishAgrahari.Program.Base.Show()' because it is not marked virtual, abstract, or override.

Sealed Keyword

Sealed keyword can be used to stop method overriding in a derived classes.

By default, all methods are sealed, which means you can't override them, so that "sealed" keyword is redundant in this case and compiler will show you an error when you'll try to make sealed already sealed method. But if your method was marked as virtual in a base class, by overriding and marking this method with "sealed" will prevent method overriding in derived classes.

See the following example:

C#
namespace PolymorphismByManishAgrahari
{
    class Program
    {
        public class Base
        {

public sealed void Show()//This Line will give an error - "cannot
{                      //be sealed because it is not an override"

                Console.WriteLine("This is Base Class.");
            }
        }

        public class Derived : Base
        {
            public void Show()
            {

                Console.WriteLine("This is Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBaseReference = new Derived();
            objBaseReference.Show();// Output ---------> This is Base Class.

            Console.ReadLine();
        }
    }
}

Error: 'PolymorphismByManishAgrahari.Program.Base.Show()' cannot be sealed because it is not an override.

To remove error from the above program, use the following:

C#
namespace PolymorphismByManishAgrahari
{
    class Program
    {
        public class Base
        {

            public virtual void Show()
            {
                Console.WriteLine("This is Base Class.");
            }
        }

        public class Derived : Base
        {
            public override sealed void Show()
            {

                Console.WriteLine("This is Derived Class.");
            }
        }

        static void Main(string[] args)
        {
            Base objBaseReference = new Derived();
            objBaseReference.Show();// Output ---> This is Derived Class.

            Console.ReadLine();
        }
    }
}

Output ---> This is Derived Class.

Summary

  1. It is not compulsory to mark the derived/child class function with override keyword while base/parent class contains a virtual method.
  2. Virtual methods allow subclasses to provide their own implementation of that method using the override keyword.
  3. Virtual methods can't be declared as private.
  4. You are not required to declare a method as virtual. But, if you don't, and you derive from the class, and your derived class has a method by the same name and signature, you'll get a warning that you are hiding a parent's method.
  5. A virtual property or method has an implementation in the base class, and can be overridden in the derived classes.
  6. We will get a warning if we won't use Virtual/New keyword.
  7. Instead of Virtual, we can use New keyword.

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionPolymorphism Pin
Member 147975449-Apr-20 9:53
Member 147975449-Apr-20 9:53 
Questiongood article.. Pin
gulumal9-Jun-17 4:23
gulumal9-Jun-17 4:23 
QuestionMy vote 1 Pin
Member 1265872430-May-17 8:10
Member 1265872430-May-17 8:10 
PraiseAwesome Pin
Ammar Shaukat30-Nov-16 22:31
professionalAmmar Shaukat30-Nov-16 22:31 
Questiondon't upload the wrong programs Pin
Member 1258694815-Jun-16 22:26
Member 1258694815-Jun-16 22:26 
QuestionNice Plagiarism Pin
Member 1117748420-May-16 6:57
Member 1117748420-May-16 6:57 
QuestionHow can we implement abstraction and polymorphism in the web application (.net) ? Pin
ParminderPalSingh6-Feb-16 1:10
professionalParminderPalSingh6-Feb-16 1:10 
Questiongood Pin
Member 82274042-Feb-16 8:55
Member 82274042-Feb-16 8:55 
QuestionStatement correction Pin
prashant zapate24-Nov-15 7:17
prashant zapate24-Nov-15 7:17 
Questionpolymorphism Pin
Pankaj Maurya20-Nov-15 23:13
Pankaj Maurya20-Nov-15 23:13 
BugMinor bug in this code. Pin
Member 1085935519-Apr-15 2:11
Member 1085935519-Apr-15 2:11 
QuestionVote 5 Pin
zhshqzyc13-Mar-15 5:28
zhshqzyc13-Mar-15 5:28 
GeneralMy vote of 1 Pin
Member 110244181-Jan-15 23:00
Member 110244181-Jan-15 23:00 
SuggestionStatic or compile time polymorphism Pin
S.SAKTHYBAALAN30-Nov-14 15:03
S.SAKTHYBAALAN30-Nov-14 15:03 
Questionabout polymorphism in .net Pin
Member 1116436219-Oct-14 1:09
Member 1116436219-Oct-14 1:09 
GeneralAwsome concept of Polymorphism vote of 5 Pin
Ehtesham Mehmood2-Oct-14 15:41
professionalEhtesham Mehmood2-Oct-14 15:41 
GeneralMy vote of 5 Pin
karthik cad/cam23-Sep-14 4:14
karthik cad/cam23-Sep-14 4:14 
QuestionI have a doubt Pin
Rahul VB14-May-14 6:41
professionalRahul VB14-May-14 6:41 
QuestionSuperb Pin
Sagar A A22-Jan-14 0:06
Sagar A A22-Jan-14 0:06 
QuestionMy vote of 5 Pin
Aydin Homay10-Dec-13 8:37
Aydin Homay10-Dec-13 8:37 
Generalnow i got full map of polymorphism.. Pin
Member 1022114112-Nov-13 4:24
Member 1022114112-Nov-13 4:24 
GeneralMy vote of 5 Pin
GregoryW12-Sep-13 1:12
GregoryW12-Sep-13 1:12 
GeneralMy vote of 5 Pin
TanzeelurRehman20-Aug-13 20:46
TanzeelurRehman20-Aug-13 20:46 
GeneralMy vote of 3 Pin
mungflesh15-Jul-13 4:54
mungflesh15-Jul-13 4:54 
GeneralMy vote of 5 Pin
ThatsAlok14-Jul-13 20:52
ThatsAlok14-Jul-13 20:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.