The second issue came about when considering what the workaround would be for this.
I want the return value of the function to only be contained within the actual range of values of the actual type of
TReturn. If I were to force the parameter & return type of this function to be
TReturn? as you suggest (and as I had considered), the battle is lost. The caller just ends up with a return value it can’t use in places typed as
TReturn (it just passes the problem down the line). Instead, the user of this function should have the error be presented to them as an error in their specification of the
defaultReturnValue argument; the compiler should present an error to the user that
defaultReturnValue is not a possible value of
TReturn (since at the call-site the compiler will actually know what
TReturn is—since the type of
visitor will be known).
Along the path of consideration for workarounds was creating to versions of the function:
A single parameter version that doesn’t take a user-provided default return value (using
null as an assumed default return value) that can only be called with nullable
One that does take a user-provided parameter
defaultReturnValue. This version solves the figuring of the default return value by leaving that to the user to explicitly provide (ie. there is no default value provided for that parameter).
Then I realized that this workaround would not be possible as AFAIK there is no syntax for specifying an exclusively nullable type in that specialized first version of the function. Is there, maybe?
That was the second issue that arose.