A quiz can keep the same validation and acceptance rule while changing how it awards points. The useful boundary is between the evaluator and the scoring formula: the evaluator asks an interface for points, and the startup code supplies the implementation.
This tutorial builds that boundary in a console app, then runs the same acceptance cases against two real policies. It uses the base class library, with no packages, database, ASP.NET, or DI container. If interfaces or constructors are new to you, start with Lesson 13: Interfaces and Lesson 7: Classes.
Define the boundary before choosing a formula
Dependency inversion means the evaluator depends on the abstraction it needs, rather than on a particular scoring class. The two scoring classes implement that abstraction. Microsoft describes this direction of dependency in its architectural principles. Here, everything lives in one file to make the relationship visible; separate assemblies are not required to demonstrate it.
Constructor injection is how we supply the chosen object. The caller constructs a policy and passes it to the evaluator. A container can automate object creation, but these ordinary constructor calls are sufficient for this app. Microsoft’s dependency injection overview describes abstracting dependencies and supplying them through constructors; its hosting and container examples are additional machinery we do not need here.
The application’s rules are deliberately small:
- A quiz has ten questions. The evaluator accepts a correct-answer count from 0 through 10 and rejects other counts.
- The practice policy awards ten points per correct answer.
- The tournament policy awards fifteen per correct answer, subtracts five per wrong answer, and floors the result at zero.
- The evaluator accepts a result with at least 70 points, whichever policy produced those points.
These are rules for this example, not a standard grading system. Six correct answers produce 60 practice points and 70 tournament points, so changing the policy intentionally changes acceptance for that input.
Run the complete example
The program below was built and run for .NET 10 in an offline Linux container, with compiler warnings treated as errors. The .NET 10 target uses C# 14 by default, as documented in C# language versioning. It does not require preview language features.
With a .NET 10 SDK installed, create a console project, replace its entire Program.cs with the listing, and run it:
dotnet new console --framework net10.0 --name ScoringDemo
cd ScoringDemo
dotnet run
using System;
internal static class Program
{
private static void Main()
{
var cases = new[]
{
(Correct: 0, Practice: 0, Tournament: 0),
(Correct: 3, Practice: 30, Tournament: 10),
(Correct: 5, Practice: 50, Tournament: 50),
(Correct: 6, Practice: 60, Tournament: 70),
(Correct: 7, Practice: 70, Tournament: 90),
(Correct: 10, Practice: 100, Tournament: 150)
};
var policies = new (string Name, IScoringPolicy Policy)[]
{
("Practice", new PracticeScoring()),
("Tournament", new TournamentScoring())
};
foreach (var (name, policy) in policies)
{
var evaluator = new QuizEvaluator(policy);
foreach (var test in cases)
{
int expected = name == "Practice" ? test.Practice : test.Tournament;
var result = evaluator.Evaluate(test.Correct);
Require(result.Points == expected, $"{name}: score for {test.Correct}");
Require(result.Accepted == (expected >= 70), $"{name}: acceptance");
}
foreach (int invalid in new[] { -1, 11 })
{
try
{
evaluator.Evaluate(invalid);
throw new InvalidOperationException("Invalid answer count was accepted.");
}
catch (ArgumentOutOfRangeException error)
{
Require(error.ParamName == "correctAnswers", "Range error parameter");
}
}
var sixCorrect = evaluator.Evaluate(6);
Console.WriteLine($"{name}: 6 correct => {sixCorrect.Points} points; accepted={sixCorrect.Accepted}");
}
try
{
_ = new QuizEvaluator(null!);
throw new InvalidOperationException("Null policy was accepted.");
}
catch (ArgumentNullException error)
{
Require(error.ParamName == "policy", "Null error parameter");
}
Console.WriteLine("Passed: 12 scoring cases, 4 range checks, 1 null check.");
}
private static void Require(bool condition, string message)
{
if (!condition)
throw new InvalidOperationException(message);
}
}
internal interface IScoringPolicy
{
// Precondition: correctAnswers is in the inclusive range 0..10.
int Score(int correctAnswers);
}
internal sealed class PracticeScoring : IScoringPolicy
{
public int Score(int correctAnswers) => correctAnswers * 10;
}
internal sealed class TournamentScoring : IScoringPolicy
{
public int Score(int correctAnswers) => Math.Max(0, correctAnswers * 15 - (10 - correctAnswers) * 5);
}
internal sealed class QuizEvaluator
{
private readonly IScoringPolicy policy;
public QuizEvaluator(IScoringPolicy policy)
{
this.policy = policy ?? throw new ArgumentNullException(nameof(policy));
}
public (int Points, bool Accepted) Evaluate(int correctAnswers)
{
if (correctAnswers < 0 || correctAnswers > 10)
throw new ArgumentOutOfRangeException(nameof(correctAnswers));
int points = policy.Score(correctAnswers);
return (points, points >= 70);
}
}
Follow the dependencies
IScoringPolicy defines one operation: return points for a valid answer count. Both policies expose a matching public method. An interface defines a contract that its implementing types satisfy; see the current Microsoft interface guide for the language rules.
QuizEvaluator stores only an IScoringPolicy. Its constructor refuses a null policy. Its Evaluate method checks the answer count, calls the policy, and compares the returned points with 70. It contains no branch that selects practice or tournament scoring, and it never constructs either implementation.
The policy methods assume the documented 0–10 precondition; validation happens at the evaluator boundary. Call policies through that boundary in this design. If they later become standalone public APIs, decide where their own input validation belongs before exposing them.
The policies array in Main is the composition point: it constructs both concrete implementations and supplies each to a fresh evaluator. In an application that needs only one policy, this is where you would choose which one to construct. Swapping policies means supplying a different object when constructing an evaluator; it does not mutate an existing evaluator.
The test harness uses the policy name to select expected values. That branch belongs to the checks, not to production evaluation. Keeping policy selection there is what lets the evaluator stay the same when a scoring formula changes.
Check behavior through the same evaluator
Each policy runs through the same six input rows: 0, 3, 5, 6, 7, and 10 correct answers. Every row checks both the expected score and acceptance. Expected scores are written explicitly in the table in Main, so the checks do not merely recompute each policy’s formula.
| Correct answers | Practice points / accepted | Tournament points / accepted |
|---|---|---|
| 0 | 0 / no | 0 / no |
| 3 | 30 / no | 10 / no |
| 5 | 50 / no | 50 / no |
| 6 | 60 / no | 70 / yes |
| 7 | 70 / yes | 90 / yes |
| 10 | 100 / yes | 150 / yes |
The program also checks −1 and 11 through each evaluator and checks a null constructor argument. A failed check throws an exception. Successful execution produces exactly this output on the verified Linux configuration:
Practice: 6 correct => 60 points; accepted=False
Tournament: 6 correct => 70 points; accepted=True
Passed: 12 scoring cases, 4 range checks, 1 null check.
During verification, the complete stdout was compared with this expected text as well as running the in-program assertions. The build reported zero compiler warnings and zero errors. These checks cover the stated examples and boundaries; they are not a proof about every possible future policy.
Keep the abstraction as small as the decision
A third formula would implement the same scoring contract and be supplied at the composition point. Add explicit expected values for it to the shared checks. If the new formula needs elapsed time or partial credit, revisit the contract: an answer count alone may no longer describe the required input.
For one permanent formula, a direct method can be easier to maintain. This interface earns its place when the evaluator must support different scoring policies while retaining the same validation and acceptance workflow. A DI container becomes a separate choice about assembling the application; the policy boundary already works with constructors.