public bool TryGetCustomerId(out Guid customerId)
{
customerId = Guid.Empty;
if (_contextAccessor.HttpContext?.Request.Headers.TryGetValue(CustomKnownHeaders.CustomerId,
out var values) ?? false)
{
return Guid.TryParse(values.FirstOrDefault(), out customerId);
}
return false;
}
After migrating from .NET Core 3.1 to .NET 5 shows an error "Use of unassigned local variable" for out parameter variable.
Error shows in "values" variable.
Error – "Use of unassigned local variable ‘values’"
2
Answers
I tested something similar in netcore3.1 and got the same error..
Are you really sure the code works in netcore3.1?
Looks like this is one of those cases where the compiler just can’t tell the variable has been definitely assigned – see "conditional access coalesced to a bool constant" here. You might have to rewrite your code to help it out:
This appears to be a bug or at least limitation in the compiler. It apparently doesn’t realize that the line:
will never execute unless
_contextAccessor.HttpContext
is non-null
,TryGetValue
is called andvalues
is assigned a value.Notably changing
?? false
to== true
(which is how I usually handle this exact scenario) doesn’t make a difference. Apparently, the fact thatTryGetValue
might not be called is enough for the compiler to treat any subsequent use ofvalues
as potentially unassigned, even thoughvalues
CANNOT be unassigned in the only branch in which it’s being used.It’s hard to look at this as anything other than a bug in the compiler which should probably be reported at https://github.com/dotnet/roslyn.
Edit
This does not appear to be an issue in Visual Studio 2022 (even in .NET5 projects), so it seems MS did recognize the bug and fix it. I only see it when opening and compiling the project using 2019.