C# and .NET • Modern C# baseline
Interfaces and Composition
Depend on small capabilities and combine behavior rather than forcing deep inheritance.
An interface defines a contract that unrelated implementations can satisfy. Constructor injection makes dependencies visible and easier to replace in tests. Composition lets an object delegate work to collaborators without coupling every type to a shared base class.
Key points
- Keep interfaces focused on client needs.
- Avoid creating an interface for every class without a design reason.
Example
interface IClock
{
DateTimeOffset UtcNow { get; }
}
sealed class ReportService(IClock clock)
{
public DateTimeOffset CreatedAt => clock.UtcNow;
}
What to expect
ReportService receives time through an IClock dependency, making its behavior controllable in tests.
Practice exercise
Create a fake clock for a test and verify the report timestamp without waiting for wall-clock time.
Key idea: Make dependencies explicit and use interfaces where substitution improves design or testing.