C#:C# Inheritance, Virtual Methods, and Interfaces
C#•Inheritance & Interfaces

C# Inheritance, Virtual Methods, and Interfaces

Learn class inheritance, the override and virtual keywords, and interface contracts in C#.

Syntax

public class Derived : Base, IInterface { public override void Execute() {} }

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
virtualKeywordAllows method to be overridden in derived classes.
overrideKeywordExplicitly overrides a virtual or abstract base method.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C# locally:

using System;

public interface IHealthCheckable {
    string CheckStatus();
}

public class BaseService : IHealthCheckable {
    public string ServiceName { get; }

    public BaseService(string name) {
        ServiceName = name;
    }

    public virtual string CheckStatus() {
        return $"{ServiceName}: OK";
    }
}

public class DatabaseService : BaseService {
    public int ActiveConnections { get; }

    public DatabaseService(string name, int connections) : base(name) {
        ActiveConnections = connections;
    }

    public override string CheckStatus() {
        return $"{base.CheckStatus()} (Connections: {ActiveConnections})";
    }
}

public class Program {
    public static void Main() {
        IHealthCheckable service = new DatabaseService("PostgresCluster", 42);
        Console.WriteLine(service.CheckStatus());
    }
}
Expected Output:
PostgresCluster: OK (Connections: 42)

How It Works: Step-by-Step

  • Lines 3-5: Defines interface contract IHealthCheckable.
  • Lines 7-17: BaseService declares virtual CheckStatus method.
  • Lines 19-29: DatabaseService overrides method and invokes base.CheckStatus().

Key Concepts

  • In C#, methods are non-virtual by default; you must explicitly mark them virtual.
  • Derived classes must specify override when overriding a virtual method.
  • A class can inherit from one base class and implement multiple interfaces.

Common Mistake: Omitting the override keyword when overriding a virtual method

Omitting override hides the base method (warning CS0114) instead of overriding it polymorphically.

❌ Incorrect
public string CheckStatus() // Hides base method!
✅ Correct
public override string CheckStatus() // Proper polymorphic override

Related C# Tutorials & Compiler

Run and test C# on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C# Online Compiler