0
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

Mufasatheking
  • 387
  • 2
  • 6
  • 16
  • I believe you must define the variable `int idRouteParam = 0;` before if condition, stop at if condition while debug and see if `RouteValues has this variable and value in it. – sairfan Sep 09 '22 at 15:32
  • RouteValueDictionary implements `IDictionary`. From the compiler point of view it can contain tuple `{ "requiredId", null}`. In this case `TryGetValue("requiredId", out var idRouteParam)` will place null into the idRouteParam and return true. I don't remember if it is feasible to make such http request in reality, but it is definitelly feasible to pass string into it. In this case you'll have a runtime while converting string to int. – Vyacheslav Benedichuk Sep 09 '22 at 15:33
  • @sairfan he won't be able to use `TryGetValue` in this case. – Vyacheslav Benedichuk Sep 09 '22 at 15:35
  • By the way. In code variable is named as `idRouteParam` in question it is named `groupRouteParam` is the code relevant to the question? – Vyacheslav Benedichuk Sep 09 '22 at 15:36
  • Sorry yes idRouteparam and groupRouteParam are the same variable, i changed it to make it easier to understand but forgot to change it in the error message – Mufasatheking Sep 09 '22 at 16:18

2 Answers2

1

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.

Iridium
  • 23,323
  • 6
  • 52
  • 74
0

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

Mufasatheking
  • 387
  • 2
  • 6
  • 16