Thursday 17 December 2020

Virtual Method in C# - Polymorphism

The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. A real-life example of polymorphism, a person at the same time can have different characteristics. Like a man at the same time is a father, a husband, an employee. So the same person posses different behavior in different situations. This is called polymorphism. Polymorphism is considered as one of the important features of Object Oriented Programming.

In C++ polymorphism is mainly divided into two types:

  • Compile time Polymorphism
  • Runtime Polymorphism

What Is A Virtual Method?(Function Overriding)

A virtual method is a class method that offers functionality to the programmer to override a method in the derived class that has the same signature. Virtual methods are mainly used to perform polymorphism in the OOPs environment.

A virtual method can have an implementation in both derived and base classes. It is mainly used when a user needs to have more functionality in the derived class.

A virtual method is first created in a base class and then it is overridden in the derived class. A virtual method can be created in the base class by using the “virtual” keyword and the same method can be overridden in the derived class by using the “override” keyword.

Virtual Methods: Few Points To Remember

  • The virtual method in the derived class has the virtual keyword and the method in derived class should have an override keyword.
  • If a method is declared as a virtual method in the base class, then it’s not always required by the derived class to override that method i.e. its optional to override a virtual method in the derived class.
  • If a method has the same definition in both the base and derived class then it’s not required to override the method. Override is only required if both have a different definition.
  • The overriding method allows us to use more than one form for the same method, hence it also shows polymorphism.
  • All the methods are non-virtual by default.
  • A virtual modifier cannot be used together with Private, Static, or Abstract modifiers.
When a method is declared as a virtual method in a base class and that method has the same definition in a derived class then there is no need to override it in the derived class. But when a virtual method has a different definition in the base class and the derived class then there is a need to override it in the 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.
 

Virtual Method in C#

  1. By default, methods are non-virtual. We can't override a non-virtual method.
  2. We can't use the virtual modifier with the static, abstract, private or override modifiers.

What Is The Use Of Virtual Keyword In C#?

The virtual keyword in C# is used to override the base class member in its derived class based on the requirement.

A virtual keyword is used to specify the virtual method in the base class and the method with the same signature that needs to be overridden in the derived class is preceded by override keyword.

Difference Between Abstract Method And Virtual Method

Virtual methods contain implementation and allow the derived class to override it whereas the abstract method does not offer any implementation and it forces the programmers to write override methods in the derived class.

Hence, in simple words, the abstract methods don’t have any code inside them whereas the virtual method has its own implementation.

Difference Between Virtual And Override In C#

The virtual keyword is usually followed by the signature of the method, property, etc. and allows it to be overridden in the derived class. The override keyword is used in the derived class with the same method/property signature as in the base class to achieve override in the derived class.

Is It Mandatory To Override Virtual Method In C#?

The compiler will never enforce programmers to override a virtual method. It’s not always required by the derived class to override the virtual method.

Example

Let’s have a look at an example to understand more clearly about the virtual methods.

In this example, we will be using two different methods in the base class, the first one is a non-virtual method and the other one is a virtual method with the virtual keyword. Both these methods will be overridden in the derived class.

Let us have a look:

Program

using System;
                     
public class Program
     
     {
       public static void Main(string[] args)
       {
           calculate calc = new calculate ();
           numbers nmbr = calc;
           calc.addition();
           nmbr.addition();
           calc.subtraction();
           nmbr.subtraction();
 
        }
    }
 
    public class numbers
    {
       public void addition(){
      Console.WriteLine("This is addition method");
     }
 
      public virtual void subtraction(){
      Console.WriteLine("This is subtraction method");
       }
 
    }
 
    public class calculate : numbers
    {
          public void addition(){
 
          Console.WriteLine("This is addition method in the derived class");
       }
 
       public override void subtraction(){
 
       Console.WriteLine("This is subtraction method override in derived class");
       }
    }

Output

The output of the above program is:

This is addition method in the derived class
This is addition method
This is subtraction method override in derived class
This is subtraction method override in derived class

Explanation

In the above example, we have two classes i.e. Number and Calculate. The base class Number has two methods i.e. addition and subtraction where addition is a non-virtual method and subtraction is a virtual method. Hence, when we execute this program the base class virtual method “addition” is overridden in the derived class Calculate.

In another class “Program” we create an entry point to create an instance of the derived class Calculate and then we assign the same instance to the instance object of the base class.

When we call the virtual and non-virtual methods by using the class instances then we see that the virtual method got overridden by using both the instances whereas the non-virtual method was overridden only while calling the derived class.

Conclusion :

The virtual keyword is useful in modifying a method, property, indexer, or event. When you have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual functions. The virtual functions could be implemented differently in different inherited class and the call to these functions will be decided at runtime.

Example :

using System;

namespace PolymorphismApplication {
   class Shape {
      protected int width, height;
   
      public Shape( int a = 0, int b = 0) {
         width = a;
         height = b;
      }

      public virtual int area() {
         Console.WriteLine("Parent class area :");
         return 0;
      }
   }

   class Rectangle: Shape {
      public Rectangle( int a = 0, int b = 0): base(a, b) {

      }

      public override int area () {
         Console.WriteLine("Rectangle class area ");
         return (width * height);
      }
   }

   class Triangle: Shape {
      public Triangle(int a = 0, int b = 0): base(a, b) {
   }

   public override int area() {
      Console.WriteLine("Triangle class area:");
      return (width * height / 2);
   }
}

class Caller {
   public void CallArea(Shape sh) {
      int a;
      a = sh.area();
      Console.WriteLine("Area: {0}", a);
   }
}

class Tester {
   static void Main(string[] args) {
      Caller c = new Caller();
      Rectangle r = new Rectangle(10, 7);
      Triangle t = new Triangle(10, 5);

      c.CallArea(r);
      c.CallArea(t);
      Console.ReadKey();
   }
   }
}

    2 comments:

    1. Thank you for your post. This is excellent information. It is amazing and wonderful to visit your site. For more info:- Xamarin App Development

      ReplyDelete

    All About .NET MAUI

      What’s .NET MAUI? .NET MAUI (.NET Multi-platform App UI) is a framework for building modern, multi-platform, natively compiled iOS, Androi...

    Ads2