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.

asked Feb 15, 2020 at 21:24
\$\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);
}
answered Feb 15, 2020 at 22:01
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.