Search code examples
c#.net-coreout-parametersunassigned-variablenull-conditional-operator

Error CS0165 Use of unassigned local variable 'json'


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


Solution

  • 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;
    }