skip to Main Content

I have the following code:

var keyValuePairs = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonbytes);
var claims = keyValuePairs.Select(kvp => new Claim(kvp.Key, kvp.Value.ToString()));

As you can see my ide shows me a Nullable warning.

vscode warning

I know that I have to check if a variable is null before using it to get rid of such a warning. But I don’t know how to do it with dynamic variables in a linq query..?

I hope someone can show me how I can avoid such a warning in this situation.

4

Answers


  1. Chosen as BEST ANSWER

    as pazcal said already i can use a ! after the object to escape such a warning. Many thanks for that hint.

    Anyway, i've changed my function now to this:

    private IEnumerable<Claim> ParseClaimsFromJwt(string jwt)
    {
        if (jwt!=null && !String.IsNullOrEmpty(jwt)) {
            var payload = jwt.Split('.')[1];
            var jsonbytes = ParseBase64WithoutPadding(payload);
            var keyValuePairs = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonbytes);
            if (keyValuePairs!=null && keyValuePairs.Count > 0) {
                var claims = keyValuePairs!.Select(kvp => new Claim(kvp.Key!, kvp.Value!.ToString()!));
                return claims;
            } else {
                throw new Exception("Error while deserializing jwt json string.");
            }
        } else {
            throw new Exception("jwt value cannot be empty or null");
        }            
    }
    

    I hope, that this is safe now :-)

    Many thanks for your help.


  2. The IDE gives you this warning as this variable might be null when it hits this line.

    If you are fully confident that this will never be the case, you can use the ! to escape these warnings:

    keyValuePairs!.Select(kvp => new Claim(kvp.Key, kvp.Value!.ToString())!);
    

    If 1 of the properties might be null you can escape these:

    keyValuePairs?.Select(kvp => new Claim(kvp.Key, kvp.Value?.ToString()));
    
    Login or Signup to reply.
  3. In your .csproj file, you will find like this

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <TargetFramework>netstandard2.1</TargetFramework>
        <Nullable>enable</Nullable>
      </PropertyGroup>
    
    </Project>
    

    This <Nullable>enable</Nullable> field gonne be disable. I think this is your solution. But not safe one.

    Login or Signup to reply.
  4. var claims = keyValuePairs?.Select(kvp => new Claim(kvp.Key, kvp.Value.ToString() ?? string.Empty));
    

    How about this?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search