RouteValues.TryGetValue gives "Local variable 'X' might not be initialized before accessing" error even if the result is true?

236 Views Asked by At
if (!this._contextAccessor.HttpContext?.Request.RouteValues.TryGetValue("requiredId", out 
var idRouteParam) ?? true)
            return Task.CompletedTask;

var id = (int)idRouteParam;

I figured by the time it got to the cast everything would work but I keep getting this compiler error "Local variable 'idRouteParam' might not be initialized before accessing" and cant figure out why

2

There are 2 best solutions below

3
Iridium On

I would suspect that this is a limitation of definite assignment analysis in the compiler, however only minor adjustment is required to get it to compile, here are a couple of options you could choose from:

Compare with Boolean:

if (this._contextAccessor.HttpContext?.Request.RouteValues.TryGetValue("requiredId", out var idRouteParam) != true)
    return Task.CompletedTask;

var id = (int)idRouteParam;

Bracket to perform the null-coalesce before the !:

if (!(this._contextAccessor.HttpContext?.Request.RouteValues.TryGetValue("requiredId", out var idRouteParam) ?? false))
    return Task.CompletedTask;

var id = (int)idRouteParam;

With either of the above changes the compiler is able to determine that idRouteParam is always assigned before use.

0
Mufasatheking On

Started working after updating my IDE and restarting my computer. Very strange error.