Skip to main content

Virtual Method in C#

A virtual method is a method that can be redefined in derived classes. A virtual method has an implementation in a base class as well as derived the class. It is used when a method's basic functionality is the same but sometimes more functionality is needed in the derived class. A virtual method is created in the base class that can be overriden in the derived class. We create a virtual method in the base class using the virtual keyword and that method is overriden in the derived class using the override keyword.
When a method is declared as a virtual method in a base class then that method can be defined in a base class and it is optional for the derived class to override that method. The overriding method also provides more than one form for a method. Hence it is also an example for polymorphism.
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. 

Difference between virtual and non-virtual methods

We have two classes; one is a "Vehicle" class and another is a "Cart" class. The "Vehicle" class is the base class that has two methods; one is a virtual method "Speed()" and another is a non-virtual method "Average()". So the base class virtual method "Speed()" is overriden in the sub class. We have one more class "Program" (the execution class) that has an entry point where we create an instance of sub class "Cart" and that instance is assigned to the base class "Vehicle" type. When we call virtual and non-virtual methods by both class's instance then according to the run type the instance virtual method implementation is invoked; in other words both class's instances invoke the subclass override method and the non-virtual method invoked is determined based on the instance of the class.
using System;  
  
namespace VirtualExample  
{     
    class Vehicle  
    {     
       public double distance=0.0;  
       public double hour =0.0;  
       public double fuel =0.0;   
  
       public Vehicle(double distance, double hour, double fuel)  
       {  
           this.distance = distance;  
           this.hour = hour;  
           this.fuel = fuel;  
       }  
  
       public void Average()  
       {  
           double average = 0.0;  
           average = distance / fuel;  
           Console.WriteLine("Vehicle Average is {0:0.00}", average);  
       }  
  
       public virtual void Speed()  
       {  
           double speed = 0.0;  
           speed = distance / hour;  
           Console.WriteLine("Vehicle Speed is {0:0.00}", speed);  
       }  
    }   
  
    class Car : Vehicle  
    {  
        public Car(double distance, double hour, double fuel)  
            : base(distance, hour, fuel)  
        {  
        }  
      public void Average()  
        {  
            double average = 0.0;  
            average = distance / fuel;  
            Console.WriteLine("Car Average is {0:0.00}", average);  
        }  
  
        public override void Speed()  
        {  
            double speed = 0.0;             
            speed = distance / hour;  
            Console.WriteLine("Car Speed is {0:0.00}", speed);  
        }  
    }   
  
    class Program  
   {  
        static void Main(string[] args)  
        {  
             double distance,hour,fuel=0.0;  
             Console.WriteLine("Enter the Distance");  
             distance = Double.Parse(Console.ReadLine());  
             Console.WriteLine("Enter the Hours");  
             hour = Double.Parse(Console.ReadLine());  
             Console.WriteLine("Enter the Fuel");  
             fuel = Double.Parse(Console.ReadLine());  
             Car objCar = new Car(distance,hour,fuel);  
             Vehicle objVeh = objCar;  
             objCar.Average();  
             objVeh.Average();  
             objCar.Speed();  
             objVeh.Speed();  
            Console.Read();  
        }         
    }  
}
Virtual Method in C#

Invoked Virtual Method that override and not override in derived classes

We have three classes "Shape","Rectangle" and "Circle". Class "Shape" is a base class. Both "Rectangle" and "Circle" are derived classes from the base class. Base class "Shape" has virtual method "Area()". Virtual method "Area()" is overriden in the derived class "Rectangle" but not overriden in the derived class "Circle". When the virtual methods are overriden in a derived class and that derived class uses an instance then invokes a derived class overriden method. When a virtual method is not overriden in a derived class and uses that derived class instance then invokes base class virtual method.
using System;  
      
namespace VirtualExample  
{     
    class Shape  
    {     
       public double length=0.0;  
       public double width =0.0;  
       public double radius =0.0;   
  
       public Shape(double length, double width)  
       {  
           this.length = length;  
           this.width = width;            
       }  
      
       public Shape(double radius)  
       {  
           this.radius = radius;  
       }  
      
       public  virtual void Area()  
       {            
           double area = 0.0;  
           area = Math.PI * Math.Pow(radius, 2);  
           Console.WriteLine("Area of Shape is :{0:0.00} ", area);  
       }  
    }   
    
    class Rectangle  : Shape  
    {  
      
        public Rectangle(double length, double width): base(length, width)  
        {  
        }      
      
        public override void Area()  
        {  
            double area = 0.0;  
            area = length * width;  
            Console.WriteLine("Area of Rectangle is :{0:0.00} ", area);  
        }  
    }  
    class Circle : Shape  
    {  
        public Circle(double radius) : base(radius)  
        {  
        }  
    }    
      
    class Program  
    {  
        static void Main(string[] args)  
        {  
             double length,width,radius=0.0;  
             Console.WriteLine("Enter the Length");  
             length = Double.Parse(Console.ReadLine());  
             Console.WriteLine("Enter the Width");  
             width = Double.Parse(Console.ReadLine());  
             Rectangle objRectangle = new Rectangle(length, width);  
             objRectangle.Area();  
             Console.WriteLine("Enter the Radius");  
             radius = Double.Parse(Console.ReadLine());  
             Circle objCircle = new Circle(radius);  
             objCircle.Area();  
             Console.Read();  
        }         
    }  
 }
Virtual Method in C#

Popular posts from this blog

Attack on Checkbox: When data ingestion gets ugly

A fun tale of when software is much easier said than done. Disclaimer: All material in this post has been used with permission. Certain details modified for client confidentiality. TL;DR: “Just read in data from Excel files. Easy!” We were wrong. When geometry, image analysis, and a little creativity come together to save a client countless hours of struggle. Shameless plug: if data ingestion troubles are keeping you up at night, contact us ! The Project That Started It All We founded our software consultancy so we could pursue our dreams in a way that full-time jobs wouldn’t let us: a touring death metal drummer, a mad roboticist, and a one-man band. It was just three of us in Calvin’s living room when our first client called. “We need a feature for our webapp where users can upload Excel and Word files, then it ingests all the form data to a database.” Sounds easy. Read in some files, parse the relevant pieces, and store them to a database. How hard coul

What Are Containers? A Simple Guide to Containerization and How Docker Works

Docker is awesome. I was late to the party and didn’t get hands-on until last year. But Docker has quickly become one of the favorite tools. It enables software developers to package, ship and run their applications anywhere without having to worry about setup or dependencies. Combined with Kubernetes, it becomes even more powerful for streamling cluster deployments and management. I digress. Back to Docker. Docker is loved by software developers and its adoption rate has been remarkable. So what exactly is Docker? It’s a platform for building, testing, deploying and publishing containerized applications. I say platform because Docker is a set of tools for managing all-things related to containers. Containers are at the heart of Docker so that’s what we’re going to explore in depth next. What is a Container? Containers provide a way to install and run your applications in isolated environments on a machine. Applications running inside a container are limited to resources (C

REST Resource Identifier (URI) Naming – REST API Tutorial

In REST, primary data representation is called Resource .  Having a strong and consistent REST resource naming strategy – will definitely prove your one of the best design decisions in long term. The key abstraction of information in REST is a resource. Any information that can be named can be a resource: a document or image, a temporal service (e.g. “today’s weather in Los Angeles”), a collection of other resources, a non-virtual object (e.g. a person), and so on. In other words, any concept that might be the target of an author’s hypertext reference must fit within the definition of a resource. A resource is a conceptual mapping to a set of entities, not the entity that corresponds to the mapping at any particular point in time. Roy Fielding’s dissertation A resource can be a singleton or a collection . For example, “ customers ” is a collection resource and “ customer ” is a singleton resource (in a banking domain). We can identify “ customers ” collection resource using the