Sobes.tech
Senior

How does virtual differ from override in C#? The four main principles of OOP.

sobes.tech AI

Answer from AI

In C#, the keyword virtual is used to declare a method or property that can be overridden in a derived class. This means that the base class provides an implementation but allows subclasses to change the behavior.

override is used in the derived class to override a virtual method or property of the base class.

Example:

class BaseClass
{
    public virtual void Show()
    {
        Console.WriteLine("Base implementation");
    }
}

class DerivedClass : BaseClass
{
    public override void Show()
    {
        Console.WriteLine("Derived implementation");
    }
}

Here, Show in the base class is declared as virtual, and in the derived class, it is overridden using override.


Four main principles of OOP:

  1. Encapsulation — hiding the internal implementation of an object and providing access through public methods.
  2. Inheritance — the ability to create new classes based on existing ones, inheriting their properties and methods.
  3. Polymorphism — the ability of objects of different classes to respond to the same messages (methods) differently.
  4. Abstraction — highlighting the essential characteristics of an object, ignoring non-essential details.

These principles help create flexible, extensible, and maintainable software systems.

How does virtual differ from override in C#? The four… - sobes.tech