
Standalone C# Discards For Argument Null Checking

Microsoft introduced discards in C# 7.0 These are variables that are intentionally unused in code, commonly used when you have to provide a variable but you never actually need it.
One of my go-to use cases of this is a discard for a variable I’m intentionally trying to ignore, for example, a null argument check in a constructor where the service perhaps has been registered by DI.
public class ServiceOne : IServiceOne
{
private IServiceTwo _serviceTwo;
public ServiceOne(IServiceTwo serviceTwo)
{
_ = serviceTwo ?? throw new ArgumentNullException(nameof(serviceTwo), "Service not configured. Please configure in service collection.");
.....
}
}
This code uses a discard to force an assignment to serviceTwo we can then use a null coalescing operator to check the argument and throw our ArgumentNullException The original result is never needed so can be discarded.