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:
| Parameter | Type | Description |
|---|---|---|
| virtual | Keyword | Allows method to be overridden in derived classes. |
| override | Keyword | Explicitly overrides a virtual or abstract base method. |
Ready-to-Run Code Example
Executable in CompilraRun 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
C# Classes, Records, and Properties (get; set;)
Design objects using classes, auto-properties ({ get; set; }), and modern C# records.
C# Named and Optional Parameters in Method Definitions
Define flexible C# methods using optional parameters with defaults and named arguments (name: value) for order independence and clarity.
C# Exception Handling: try, catch, finally, and Exception Filters
Catch and handle exceptions with try, catch, finally, and C# exception filters (when).
C# Online Compiler
Open in Compilra IDE
Run and test C# on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.