I was working to upgrade some code to C# 8.0 and came across an interesting pattern with default parameters and non-nullable reference types. I'm working if it's clear enough to the caller.
Given this pre C# 8.0 code,
Task FooAsync(
Bar bar = null,
CancellationToken ct = default)
{
bar = bar ?? new Bar(); // some sensible default
}
the bar
parameter is flagged as one to potentially make nullable (Bar? bar = null
). This would indicate to the caller that they can pass null
.
However, if I want to encourage the caller not to pass null
for the parameter, I could do something like this in C# 8.0:
Task FooAsync(
Bar bar = null!,
CancellationToken ct = default)
{
bar ?? = new Bar(); // some sensible default
}
Is this a sensible approach to avoid passing null
into the parameter? I know the caller can still do: FooAsync(bar: null!)
but that obviously sticks out.