Inheritance/polymorphism modifiers in C#
virtual - a method with a default implementation, optionally overridable
public class OrderProcessor
{
public virtual void Process(Order order)
{
Console.WriteLine("Standardowe przetwarzanie");
}
}
public class PriorityOrderProcessor : OrderProcessor
{
public override void Process(Order order) // nadpisanie OPCJONALNE
{
Console.WriteLine("Priorytetowe");
base.Process(order); // you can call the original implementation
}
}
A derived class may, but doesn't have to override it - if it doesn't, it inherits the base behaviour. Dynamic binding (polymorphism) - the version of the method is decided by the actual type of the object at runtime, not the type of the variable.
abstract - a method without an implementation, an ENFORCED override
public abstract class OrderProcessorBase
{
public abstract void Process(Order order); // no body - no implementation at all
}
public class StandardOrderProcessor : OrderProcessorBase
{
public override void Process(Order order) // MUST override, otherwise a compile error
{
Console.WriteLine("Przetwarzanie");
}
}
A class containing an abstract method must itself be abstract - it can't be instantiated (new OrderProcessorBase() is a compile error). As we discussed with Inversion of Control - this is the foundation of the Template Method Pattern.
override - the actual overriding of a virtual/abstract method
public class Base
{
public virtual void Method() => Console.WriteLine("Base");
}
public class Derived : Base
{
public override void Method() => Console.WriteLine("Derived"); // NADPISUJE, nie ukrywa
}
Base obj = new Derived();
obj.Method(); // "Derived" - DYNAMIC binding, the actual type of the object at runtime decides
Requirements: the same signature (name, parameters, return type), and the visibility can't be narrower than that of the base method.
sealed - blocking further overriding/inheritance
On a method (must be combined with override) - "seals" a specific override, blocking further levels:
public class Base
{
public virtual void Method() { }
}
public class Middle : Base
{
public sealed override void Method() { } // the last possible override in the chain
}
public class Derived : Middle
{
public override void Method() { } // ❌ Error - Method is sealed in Middle
}
On a class - blocks inheritance entirely:
public sealed class OrderValidator
{
public void Validate(Order order) { }
}
public class CustomValidator : OrderValidator { } // ❌ Error - you can't inherit from a sealed class
Good practice: classes not designed with inheritance in mind (with no deliberately planned virtual) are worth marking as sealed, to avoid unforeseen problems when someone tries to extend them.
new - method hiding, NOT overriding
public class Base
{
public void Show() => Console.WriteLine("Base"); // BRAK virtual
}
public class Derived : Base
{
public new void Show() => Console.WriteLine("Derived"); // "new" zamiast "override"
}
Base obj = new Derived();
obj.Show(); // "Base"! - STATIC binding, the type of the VARIABLE decides at compile time
Derived obj2 = new Derived();
obj2.Show(); // "Derived" - bo typ zmiennej to Derived
This is a classic trap in interviews - new hides the base method instead of overriding it. Unlike override (dynamic binding - the actual type of the object decides), new means static binding - the type of the variable through which you call the method decides, regardless of the actual type of the object in memory.
Summary table of inheritance modifiers
| Modifier | Requires a base virtual/abstract? |
Implementation in the base? | Override required? | Binding |
|---|---|---|---|---|
virtual (on the base) |
- | Yes | Optional (override) |
Dynamic |
abstract (on the base) |
- | No | Required | Dynamic |
override (on the derived) |
Yes | - | This IS the override | Dynamic |
sealed override (on the derived) |
Yes | - | Blocks FURTHER overrides | Dynamic, frozen |
new (on the derived) |
No (works even without virtual) |
- | Doesn't override, only hides | Static |
How these two categories fit together - a full example
public abstract class ViewModelBase // class: cannot be instantiated directly
{
protected readonly ILogger _logger; // private/protected - an ACCESS modifier
protected ViewModelBase(ILogger logger) => _logger = logger;
// protected + virtual: visible to subclasses (access) AND optionally overridable (inheritance)
protected virtual void OnPropertyChanged(string propertyName) { }
// public + abstract: visible everywhere (access) AND ENFORCES an override (inheritance)
public abstract void Refresh();
}
public sealed class OrderViewModel : ViewModelBase // sealed: nobody can inherit FURTHER from this class
{
public OrderViewModel(ILogger logger) : base(logger) { }
public override void Refresh() { /* wymagana implementacja */ }
protected override void OnPropertyChanged(string propertyName)
{
Console.WriteLine($"Zmiana: {propertyName}");
base.OnPropertyChanged(propertyName);
}
}
This shows that an access modifier and an inheritance modifier are two independent, orthogonal decisions when designing every method - the first answers "who can see it", the second "whether and how it can be changed in subclasses".
When a method can be overridden in C#
The basic condition - virtual, abstract or override in the base class
A method must be explicitly marked as overridable - in C#, unlike e.g. Java, methods are NOT overridable by default.
public class Animal
{
public void MakeSound() // an ordinary method - CANNOT be overridden
{
Console.WriteLine("Some sound");
}
public virtual void Move() // virtual - CAN be overridden
{
Console.WriteLine("Moves");
}
}
public class Dog : Animal
{
// ❌ Compile error - MakeSound is not virtual, you can't use override
public override void MakeSound() { }
// ✅ OK - Move jest virtual w klasie bazowej
public override void Move()
{
Console.WriteLine("Biegnie");
}
}
Conditions that MUST be met with override
The same signature (name, parameters, return type)
public class Base
{
public virtual int Calculate(int x) => x * 2;
}
public class Derived : Base
{
// ❌ Error - a different signature (a different parameter type) is NOT an override, it is an OVERLOAD
public override int Calculate(double x) => (int)(x * 2); // won't compile with "override"
// ✅ OK - exactly the same signature
public override int Calculate(int x) => x * 3;
}
The visibility (accessibility) can't be narrowed
public class Base
{
public virtual void DoWork() { }
}
public class Derived : Base
{
protected override void DoWork() { } // ❌ Error - you can't reduce accessibility from public to protected
public override void DoWork() { } // ✅ OK - the same or wider visibility
}
No access modifier enforces overriding - a common conceptual trap
This question mixes two different categories of modifiers in C# that are easy to confuse.
Access modifiers - control visibility (who can see/call it): public, private, protected, internal, protected internal, private protected
Inheritance/polymorphism modifiers - control whether and how a method can be overridden: virtual, abstract, override, sealed, new
These are completely separate axes - you can combine them, but no access modifier on its own enforces an override.
abstract is a modifier from the second category (inheritance), not an access modifier. You can combine it with any access modifier:
public abstract void Process(Order order); // publiczne, wymuszone nadpisanie
protected abstract void Validate(Order order); // chronione, wymuszone nadpisanie
private + virtual/abstract is a compile error:
public class Base
{
private virtual void DoWork() { } // ❌ Compile error: "virtual member cannot be private"
}
private means "not visible outside this class", so a derived class can't even see this method, let alone override it. An access modifier limits the possibilities of an inheritance modifier, but doesn't replace it.
Summary - the correct answer to this question
No access modifier (
public/protected/private/internal) enforces an override - that is not their role. An access modifier answers the question "who can see/call it". Enforcing an override is the role of theabstractmodifier (a separate category - an inheritance modifier), which can be combined with any access modifier exceptprivate(becauseprivatemakes the method invisible to derived classes, so an override would be physically impossible).