Version Used: VisualStudio.16.int.d16.0stg/16.0.0-pre.2.0+28408.101.d16.0stg
C# Tools 2.11.0-beta2-63529-05+66aa49da81717aa54090a9e94c2f575ddb1959bb
When doing a Try pattern like this:
public bool TryGetSomething (out ReferenceType result)
{
if (someCondition)
{
result = /* non-null value */;
return true;
}
else
{
result = default;
return false;
}
}
With nullable types because default is used you will end up converting the out parameter to ReferenceType?.
It would be nice on the caller side if subsequently this would be supported:
if (TryGetSomething (out var result))
// result is not null and thus doesn't trigger "Possible deference of a null reference" warning
result.DoSomething ();
Today this doesn't seem to be the case with the following (real) code sample
// Caller site
public bool TryGetNextInSpan(in TextSpan span, out SyntaxNode? value)
{
if (_stack == null) {
value = default;
return false;
}
while (_stack[_stackPtr].TryMoveNextAndGetCurrent(out value))
{
if (IsInSpan(in span, /* `value` shows the dereference warning --> */ value.FullSpan))
{
return true;
}
}
_stackPtr--;
return false;
}
// Defined in class used by `_stack`
internal bool TryMoveNextAndGetCurrent(out SyntaxNode? current)
{
if (!MoveNext())
{
current = default;
return false;
}
// ItemInternal returns a non-nullable type
current = ItemInternal(_node, _childIndex);
return true;
}
There is an attribute that can be used to get this effect. @jcouv Do you recall what it is?
[System.Runtime.CompilerServices.NotNullWhenTrue] and [NotNullWhenFalse].
You'll have to include a definition in your program at the moment.
@garuma Closing as I think your question has been answered. Please let us know if it has not been answered and we'll reopen.
Most helpful comment
[System.Runtime.CompilerServices.NotNullWhenTrue]and[NotNullWhenFalse].You'll have to include a definition in your program at the moment.