Home > Back-end >  After migrating to .NET 5 shows an error "Use of unassigned local variable" for out parame
After migrating to .NET 5 shows an error "Use of unassigned local variable" for out parame

Time:01-04

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'"

CodePudding user response:

After migrating from .Net core 3.1 to .Net 5 shows an error "Use of unassigned local variable"

I tested something similar in netcore3.1 and got the same error..

enter image description hereAre 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:

public bool TryGetCustomerId(out Guid customerId)
{
    customerId = Guid.Empty;
    string[] values = null;
    if (_contextAccessor.HttpContext?.Request.Headers.TryGetValue(CustomKnownHeaders.CustomerId,
        out values) ?? false)
    {
        return Guid.TryParse(values.FirstOrDefault(), out customerId);
    }

    return false;
}

CodePudding user response:

This appears to be a bug or at least limitation in the compiler. It apparently doesn't realize that the line:

return Guid.TryParse(values.FirstOrDefault(), out customerId);

will never execute unless _contextAccessor.HttpContext is non-null, TryGetValue is called and values 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 that TryGetValue might not be called is enough for the compiler to treat any subsequent use of values as potentially unassigned, even though values 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.

  •  Tags:  
  • Related