Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading