C# Interfaces
Depend on a fee policy contract and substitute two implementations without coupling the caller to their classes.
How it works
An interface describes operations that a caller may rely on. A class can implement several interfaces when it genuinely provides several capabilities. Prefer narrow interfaces whose behaviour can be explained and tested; a large interface forcing unrelated methods onto every implementation is harder to maintain. Constructor injection can supply a collaborator without a dependency-injection framework. Use composition for has-a relationships instead of building an inheritance hierarchy merely to reuse code.
Run it locally
Use the .NET 10 SDK with C# 14 in a separate console lab. Create an empty project once with dotnet new console --framework net10.0, then replace Program.cs with this complete source and add any supporting files shown. Keep only one lesson entry point in the project. C# does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.
dotnet build -p:LangVersion=14.0 -p:Nullable=enable -p:TreatWarningsAsErrors=true
dotnet run --no-buildUse the SDK’s project workflow; the review compiles against its matching reference assemblies and executes the results without external NuGet packages. File-writing examples belong in a private empty lab directory.
Example
using System;
internal static class Program
{
private static void Main(string[] args)
{
IFeePolicy regular = new RegularFee();
IFeePolicy supported = new SupportedFee();
Console.WriteLine($"Regular units: {regular.Units(3)}");
Console.WriteLine($"Supported units: {supported.Units(3)}");
}
}
internal interface IFeePolicy { int Units(int places); }
internal sealed class RegularFee : IFeePolicy { public int Units(int places) => places * 2; }
internal sealed class SupportedFee : IFeePolicy { public int Units(int places) => places; }
Expected result
Regular units: 6
Supported units: 3
The caller uses the same operation with two concrete policies. The fixed small input satisfies this lab’s nonnegative, nonoverflowing contract. A production policy must enforce or receive a checked domain value. Implementing another interface does not make shared mutable fields thread-safe or make two unrelated operations semantically compatible.
Consult Microsoft’s C# documentation for language and library contracts, including target-framework and version requirements.