optional/null-able OUT parameter in C#
I have a method that has several overrides. In one of the more expanded overrides, I want 开发者_如何学Goto return an OUT parameter but not in my simpler overrides. For example:
public bool IsPossible(string param1, int param2)
public bool IsPossible(string param1, int param2, out bool param3)
The way I am currently achieving this, is like so:
public bool IsPossible(string param1, int param2) {
bool temp;
return IsPossible(param1, param2, out temp);
}
Is there a better way to achieve this? Can I (or should I) use a null-able out parameter?
That looks fine to me. A out
cannot be optional for technical reasons (it needs to point to a valid instance).
Since C# 7.0 you can pass a Discard (_
) into the method:
return IsPossible(param1, param2, out _);
See: https://learn.microsoft.com/en-us/dotnet/csharp/discards
OP:
Can I (or should I) use a null-able out parameter?
A nullable out parameter won't do you much good. This:
public bool IsPossible( string param1, int param2, out bool? param3 )
{
...
}
doesn't make param3
optional. It changes the semantics of what param3
is. A bool?
(aka Nullable<bool>
) widens the domain of param3
from 2 values ( true
and false
) to 3, adding a third value (null
), usually interpreted as missing/unknown. The caller still must supply all three arguments.
Overloading IsPossible()
by providing an overload -- the "don't care" scenario -- that discards the reference parameter is the proper solution.
A 'ref' or 'out' parameter cannot have a default value.
The way you've done it is just fine. Sorry, no silver bullet.
Personally I think it is fine "as is". Another approach, though, is to return a composite return value (perhaps an immutable struct with 2 properties); that avoids the fact that some people avoid out
. I am not one of those people :p
Re the question; indeed, out/ref can't be optional.
If you wanted to get unnecessarily fancy you could give the conposite return-type a conversion to bool to allow implicit if
tests.
Yes, Nullable variables are great. You would then do something like this.
public bool? IsPossible(string param1, int param2);
var ans = IsPossible("Parm1", 1);
if (ans.HasValue)
{
//working.
}
精彩评论