3
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ could someone with high enough rep please create [c#-8.x] and [nullable-reference-types]? \$\endgroup\$ Commented Feb 15, 2020 at 21:25

1 Answer 1

4
\$\begingroup\$

My take on this is that the function signature should not lie. So if it can handle a null passed in, as it can, it should use

Bar? bar = null

Another approach could be to overload the function with another which only takes a single parameter. Something like ...

Task FooAsync(
   Bar bar,
   CancellationToken ct = default)
{
    ...
}

Task FooAsync(
   CancellationToken ct = default)
{
    return FooAsync(new Bar(), ct);
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.