1

I am trying to get value from the HttpContext with a key Correlation-Context, but I am not sure why I am getting the error while trying to use the variable json.

internal static CorrelationContext GetCorrelationContext(this IHttpContextAccessor accessor)
{
    return accessor.HttpContext?.Request.Headers.TryGetValue("Correlation-Context", out var json) is true
    ? JsonConvert.DeserializeObject<CorrelationContext>(json.FirstOrDefault())
    : null;
}

I am getting the error as:

Error   CS0165  Use of unassigned local variable 'json' 

I am using the target framework of net 5.0

Rasik
  • 1,961
  • 3
  • 35
  • 72
  • 1
    If `accessor.HttpContext?.Request` is `null` then `TryGetValue()` never gets executed, leaving `json` unassigned. – Lance U. Matthews Apr 19 '22 at 07:07
  • 2
    This is too complicated for the definite assignment rules -- even though it's obvious to us that the expression could only be `true` if `accessor.HttpContext?` is not null and thus `.TryGetValue` has executed, it doesn't follow from the (static) assignment rules. – Jeroen Mostert Apr 19 '22 at 07:07
  • Arguably the `is true` part would evaluate to `false` in the case that Lance mentioned, but I don't think we can expect the compiler to dig quite so deeply here. – ProgrammingLlama Apr 19 '22 at 07:08
  • Works for me; what version of .NET/C# are you using? I do instead get CS8604 on the `FirstOrDefault()`, as I have Nullable enabled and the version of Newtonsoft.JSON I'm using expects a non-null value to `JsonConvert.DeserializeObject()`. – sellotape Apr 19 '22 at 07:18

1 Answers1

3

Although it's obvious to us, I think it's a bit too complicated for the compiler to understand that if HttpContext is null then the statement will evaluate to false.

You can fix your method by moving adding a null check and not using ?.:

internal static CorrelationContext GetCorrelationContext(this IHttpContextAccessor accessor)
{
    if (accessor.HttpContext == null)
    {
        return null;
    }

    return accessor.HttpContext.Request.Headers.TryGetValue("Correlation-Context", out var json)
        ? JsonConvert.DeserializeObject<CorrelationContext>(json.FirstOrDefault())
        : null;
}
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • so ` HttpContext? HttpContext { get; set; }` preventing the first part to be excecuted? – Rasik Apr 19 '22 at 07:11
  • `accessor.HttpContext?.Request` will immediately return `null` if `HttpContext` is `null`. That then leaves the evaluation as `null is true`, which is of course `false`. It would appear that following the logic that far is a bit too much for the compiler at the moment, so it believes that this is a scenario where it could get into the deserialize code without `json` being assigned. – ProgrammingLlama Apr 19 '22 at 07:13