Null Object intent (a do-nothing implementation instead of null), framework examples (NullLogger<T>.Instance, NullLoggerFactory, Stream.Null, TextWriter.Null, Array.Empty<T>, Enumerable.Empty<T>, Task.CompletedTask, CancellationToken.None), returning empty collections, optional dependencies in DI, comparison with nullable reference types and the Maybe/Result approach, and when a null object masks failures.
Null Object replaces null with an object that implements the same interface and does nothing safely, so callers don't need null checks.
.NET uses it widely: NullLogger<T>.Instance, Stream.Null, TextWriter.Null, Array.Empty<T>(), Enumerable.Empty<T>(), Task.CompletedTask and CancellationToken.None. Returning an empty collection instead of null is the everyday form.
Nullable reference types solve a different problem: they make "this might be null" visible at compile time so you handle it. Null Object is for when "do nothing" is genuinely the correct behaviour, like an optional logger.
The danger is when doing nothing is wrong: a NullLogger left in production, or an empty list returned because the database call failed. Then the null object hides an error instead of preventing one.
"Null Object is a simple idea: instead of passing or returning
nulland making every caller check for it, you pass an object that implements the same interface and does nothing. If a class takes anILoggerand the caller doesn't care about logs, you give itNullLogger<T>.Instance. EveryLogcall is a no-op, and the class never needsif (_logger != null). The object is stateless, so one shared static instance is enough..NET is full of these.
NullLoggerandNullLoggerFactoryare what I use in unit tests.Stream.NullandTextWriter.Nullswallow writes and return nothing on reads.Array.Empty<T>()andEnumerable.Empty<T>()are the null objects of collections: a method that returns 'no orders' should return an empty list, not null, so callers can justforeach.Task.CompletedTaskis the null object for 'async work that has nothing to do', andCancellationToken.Noneis a token that never cancels. In application code I use it for optional collaborators: in local development I register aNullEmailSenderso the app runs without SMTP.How it relates to nullable reference types: they're complementary. Nullable reference types make 'this might be missing' explicit, so the compiler forces me to handle it. Null Object is for cases where 'missing' should behave exactly like 'present but doing nothing'. The mistake I see is using it where doing nothing is wrong. A
NullLoggerthat ends up registered in production means you have no logs during an incident. A repository that catches an exception and returns an empty list tells the UI there are no orders when the database is actually down. A null object is right when doing nothing is a correct answer; when absence is a problem, make it visible instead."
| Null object | Replaces | Behaviour |
|---|---|---|
NullLogger<T>.Instance, NullLoggerFactory.Instance |
A real logger | Ignores all log calls; IsEnabled returns false |
Stream.Null |
A real stream | Writes discarded, reads return 0 bytes |
TextWriter.Null, TextReader.Null |
Console or file writers | Discards output, reads nothing |
Array.Empty<T>(), Enumerable.Empty<T>() |
null collections |
Empty, cached, no allocation |
Task.CompletedTask, ValueTask default |
A pending task | Already completed |
CancellationToken.None |
A real token | Never cancels |
| Approach | Use when | Example |
|---|---|---|
| Null Object | Doing nothing is correct | Optional logger, metrics, notifications in dev |
| Empty collection | "None" is a valid result | GetOrders() returns [] |
Nullable return (T?) with NRT |
Absence must be handled by the caller | FindCustomer(id) returns Customer? |
TryGet pattern |
Absence is common and cheap to check | TryGetValue(key, out var value) |
| Exception / Result | Absence or failure is an error | Database unavailable, payment declined |
A notification service registered NullSmsSender when the SMS configuration section was missing, intended for local development. A configuration typo in production meant two-factor codes weren't sent for about 40 minutes, with no errors logged. The fix kept the null object for development only, made production fail at start-up with ValidateOnStart if SMS settings were missing, and added a counter for messages dropped by any null sender.
Checks that the candidate recognises Null Object in .NET, can use it for optional collaborators and empty results, and knows when it masks failures.
Green flags
Red flags
Client βββΆ Β«interfaceΒ» INotificationSender
SendAsync(message)
β² β²
SmtpNotificationSender NullNotificationSender
(real work) (does nothing, returns completed task)
The client never branches on null. Which implementation it gets is decided once, in DI configuration.
Every null that can flow into a method creates a branch the caller must remember. Missing one gives a NullReferenceException far from where the null came from. A null object removes the branch entirely when the "nothing" case has well-defined behaviour.
Framework Design Guidelines say methods returning collections should return empty collections, never null. Array.Empty<T>() returns a cached zero-length array per T, so returning it allocates nothing. In C# 12+, a collection expression [] targeting an array or IEnumerable<T> uses the same cached empty instance where possible.
With <Nullable>enable</Nullable>, a parameter typed ILogger (not ILogger?) tells callers they must pass something. Null Object gives them something sensible to pass. Conversely, a return type Customer? tells callers to handle absence; you should not return a fake "null customer" there, because then callers can't tell "found" from "not found", and a fake customer with default values can flow into pricing or emails.
NullEmailSender in development and SmtpEmailSender elsewhere, chosen by environment, not by "is the config present" (which turns typos into silent outages).ILogger<T>? logger = null and fall back to NullLogger<T>.Instance so consumers aren't forced to supply logging.NullLogger<T>.Instance instead of mocking ILogger.Null Object is dangerous when the "nothing" behaviour is indistinguishable from success and success matters: security codes, payments, audit logs, data reads. If you use one, make its use observable (log once at start-up which implementation was chosen, count dropped calls) and never select it silently in production.
ILogger null checks in a class with NullLogger<T>.Instance and delete the branches.null for "no results" to return Array.Empty<T>(); check allocations with BenchmarkDotNet.NullEmailSender only when builder.Environment.IsDevelopment() and add ValidateOnStart for SMTP options otherwise.SqlException and returns an empty list; discuss with a colleague what the UI would show during an outage.A null object for an optional dependency, registered by environment, and empty collections instead of null.
namespace Notifications;
public sealed record Notification(string To, string Subject, string Body);
public interface INotificationSender
{
Task SendAsync(Notification notification, CancellationToken ct);
}
public sealed class SmtpNotificationSender(ILogger<SmtpNotificationSender> logger) : INotificationSender
{
public async Task SendAsync(Notification n, CancellationToken ct)
{
// ... real SMTP call ...
await Task.Delay(10, ct);
logger.LogInformation("Sent {Subject} to {To}", n.Subject, n.To);
}
}
// Null Object: same interface, safely does nothing. Stateless, so one shared instance.
public sealed class NullNotificationSender : INotificationSender
{
public static NullNotificationSender Instance { get; } = new();
private NullNotificationSender() { }
public Task SendAsync(Notification notification, CancellationToken ct) => Task.CompletedTask;
}
// Callers never check for null
public sealed class SignupService(INotificationSender sender, ILogger<SignupService>? logger = null)
{
private readonly ILogger _logger = logger ?? Microsoft.Extensions.Logging.Abstractions.NullLogger<SignupService>.Instance;
public async Task RegisterAsync(string email, CancellationToken ct)
{
_logger.LogInformation("Registering {Email}", email);
await sender.SendAsync(new Notification(email, "Welcome", "Thanks for signing up"), ct);
}
}
// Program.cs: choose the null object by environment, never by "config is missing"
if (builder.Environment.IsDevelopment())
{
builder.Services.AddSingleton<INotificationSender>(NullNotificationSender.Instance);
}
else
{
builder.Services.AddOptions<SmtpOptions>()
.Bind(builder.Configuration.GetSection("Smtp"))
.ValidateDataAnnotations()
.ValidateOnStart(); // a typo fails the deployment, not 2FA codes
builder.Services.AddSingleton<INotificationSender, SmtpNotificationSender>();
}
public sealed class SmtpOptions
{
[System.ComponentModel.DataAnnotations.Required] public string Host { get; set; } = "";
}
namespace Orders;
public sealed record OrderSummary(Guid Id, decimal Total);
public sealed class OrderQueries(OrdersDbContext db)
{
// Empty collection, never null: callers can foreach and Count safely
public async Task<IReadOnlyList<OrderSummary>> RecentAsync(Guid customerId, CancellationToken ct)
{
var orders = await db.Orders
.Where(o => o.CustomerId == customerId)
.OrderByDescending(o => o.PlacedAt)
.Take(10)
.Select(o => new OrderSummary(o.Id, o.Total))
.ToListAsync(ct);
return orders; // [] when there are none
}
// Absence that must be handled: nullable return, not a fake "null order"
public Task<OrderSummary?> FindAsync(Guid id, CancellationToken ct) =>
db.Orders.Where(o => o.Id == id).Select(o => new OrderSummary(o.Id, o.Total)).SingleOrDefaultAsync(ct);
// DON'T: hiding a failure behind an empty result
// catch (SqlException) { return Array.Empty<OrderSummary>(); } // UI shows "no orders" during an outage
}
// Tests use the framework's null object instead of mocking ILogger
// var service = new SignupService(NullNotificationSender.Instance, NullLogger<SignupService>.Instance);
null from methods that return collections. Why it is wrong: Every caller must null-check, and one that forgets throws NullReferenceException. Instead: Return an empty collection ([], Array.Empty<T>()).ValidateOnStart to fail fast elsewhere.Customer? and let nullable reference types force handling.Instance.ILogger in every test just to satisfy the constructor. Why it is wrong: Noise and brittle setups. Instead: NullLogger<T>.Instance, unless the test asserts on logging.I treat Null Object as a statement: "for this collaborator, doing nothing is a correct outcome". That's true for logging in tests, optional telemetry, and empty results. It's false for anything where the absence of an effect is a failure, and there I want nullable types, exceptions or results that make the absence visible.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Null Object | Optional collaborators; no-op is correct | Can hide misconfiguration | Critical side effects |
| Empty collection | "None" is a valid result | None | Failures disguised as empty |
| Nullable return + NRT | Caller must handle absence | Null checks at call sites | When absence is never meaningful |
TryGet pattern |
Hot paths, frequent misses | Out parameters | Async methods |
| Result type / exception | Absence or failure is an error | More ceremony | Expected empty results |
If a null object is ever selected outside development, I make it observable: log which implementation was registered at start-up and count calls it dropped.
<Nullable>enable</Nullable> makes reference types non-nullable by default: string? means a value can be null and string means it can't. The compiler then warns when code might dereference null. It's purely compile-time, so nothing changes at run time. In a big codebase I migrate bottom-up: shared libraries and domain types first, because their annotations flow out to everyone else. I go project by project, or file by file with #nullable enable, and give each step a small pull request so feature work carries on. When a project is clean I make its nullable warnings errors with WarningsAsErrors=nullable, so it can't slip back. I use attributes such as [NotNullWhen] where flow analysis needs help and keep ! for real boundaries. I also watch for two things: EF Core migrations, where nullability decides whether columns are required, and public APIs, where annotations are part of the contract.
Strategy puts each variant of an algorithm behind one interface, so the code that uses it (the context) calls whichever implementation it was given instead of branching on a mode. A switch that grows with every new discount, carrier or export format becomes a set of small classes, and adding a variant means adding a class, not editing the switch (Open/Closed).
.NET uses it everywhere: IComparer<T> in List<T>.Sort, IEqualityComparer<T> in Dictionary, StringComparer.OrdinalIgnoreCase, JsonNamingPolicy.
IEnumerable<IStrategy>, or use keyed services (.NET 8+), to pick one by key.Func<T, TResult> delegate is a strategy without the ceremony.The trade-off: more types and indirection, so a short, stable switch is often clearer.
Func is a delegate that returns a value, so Func<int, string> takes an int and returns a string. Action returns void, and Predicate<T> is a delegate that takes a T and returns bool. Older APIs like List<T>.FindAll use it, while LINQ uses Func<T, bool>. Even with identical signatures they are different delegate types, so you cannot pass a Func<T, bool> variable as a Predicate<T> without wrapping it. A lambda converts to either. I declare my own delegate only when I need ref or out parameters or a meaningful name.
Last updated 18 Nov 2026.