OSC#.009: C# Interfaces — Behavior Contracts, Multiple Implementations and Testability

CSIRO server racks

Open-Source C# Programming • Foundational • Estimated study time: 45 minutes.

A monitoring application should be able to read power from different devices without requiring a separate reporting function for each implementation. A C# interface defines a contract that unrelated classes can implement. This lesson follows inheritance and runtime polymorphism and classes and encapsulation.

Learning objectives

Declare an interface; implement it in two classes; call methods through interface references; substitute a test implementation; distinguish an interface from a base class; validate measurement values.

Beginner C# tutorial demonstrating interfaces.

Behavior rather than shared implementation

The Microsoft interface guide and language specification describe the rules for implementation. A class can have one direct base class but implement multiple interfaces. In a basic interface such as IPowerSource, the caller knows the method signature without needing the implementation’s private fields. Modern C# also supports default interface members; this example intentionally uses the simpler abstract-member contract.

Circuit board components
Ingo Dierking / Wikimedia Commons, CC BY-SA 4.0. Contextual hardware photograph.

Worked example: two telemetry implementations

The reporting method uses methods and parameters and control flow. Create a console project with dotnet new console, replace Program.cs with this code and run dotnet run locally. No network connection or physical equipment is needed.

using System;

public interface IPowerSource
{
    double ReadWatts();
}

public sealed class FixedSource : IPowerSource
{
    private readonly double watts;
    public FixedSource(double watts) { this.watts = watts; }
    public double ReadWatts() { return watts; }
}

public sealed class VoltageCurrentSource : IPowerSource
{
    private readonly double volts, amps;
    public VoltageCurrentSource(double volts, double amps)
    { this.volts = volts; this.amps = amps; }
    public double ReadWatts() { return volts * amps; }
}

public static class Program
{
    public static double ReadTotal(IPowerSource[] sources)
    {
        double total = 0;
        foreach (IPowerSource source in sources)
        {
            double watts = source.ReadWatts();
            if (double.IsNaN(watts) || double.IsInfinity(watts) || watts < 0)
                throw new ArgumentException("Invalid reading");
            total += watts;
            if (double.IsInfinity(total))
                throw new ArgumentException("Total overflow");
        }
        return total;
    }
    public static void Main()
    {
        IPowerSource[] sources = {
            new FixedSource(100),
            new VoltageCurrentSource(48, 2.5)
        };
        double total = ReadTotal(sources);
        if (total != 220) throw new Exception("Unexpected total");
        Console.WriteLine("Total: " + total + " W");
        try {
            ReadTotal(new IPowerSource[] { new FixedSource(-1) });
            throw new Exception("Invalid input accepted");
        } catch (ArgumentException) {
            Console.WriteLine("Invalid input rejected");
        }
    }
}

Expected output: Total: 220 W; Invalid input rejected. The arithmetic and control flow were reviewed, but a C# compiler/runtime was unavailable, so the example was not executed.

Measurement calculation

For a DC load, P = V × I, where V is voltage in volts and I is current in amperes. The second source gives 48 × 2.5 = 120 W; the combined synthetic load is 100 + 120 = 220 W. At constant load for half an hour, E = P × t = 110 Wh. This simple formula is not a universal AC power calculation. Reject invalid values rather than treat missing measurements as zero.

Community discussion: why an interface may be useful even when only one implementation currently exists. Testability and decoupling can justify the abstraction, but not every class needs an interface.

Safety and exercises

Use synthetic data and verify units, timing, calibration and numeric ranges before adapting the example for operational monitoring. Never connect it directly to safety-critical control equipment. A. What does IPowerSource require? B. Which source calculates watts from voltage and current? C. Why can ReadTotal use either class? D. What is the total for an empty array? E. What is the total energy at 220 W for two hours? Answers: A. A ReadWatts method returning double. B. VoltageCurrentSource. C. Both implement the contract. D. Zero for this implementation; a production system may need to distinguish missing input. E. 440 Wh.

Cover: CSIRO / Wikimedia Commons, CC BY 3.0, cropped; contextual server photograph.

Editor’s Note: We volunteer daily to ensure the credibility of the information on this platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiatives, please scan the QR code below

BitcoinVersus.Tech donation QR code for 5,000 satoshis

For mobile scanning, open the article on another display and scan the QR code with a Bitcoin wallet. The voluntary donation amount is 5,000 sats. Verify the receiving address 3C9o19EH5HSiwEPyCTmEKzxhNCbo2X6TTb before sending.

BitcoinVersus.Tech publishes technology and financial journalism for informational purposes and does not provide financial, investment, or legal advice.

Leave a Reply