Search code examples
c#sonarqube

SonarQube Warning for null reference


I have 2 pieces of code where the core logic is same but SonarQube behaves different and gives me a warning:

First see the no warning snip:

NO-WARNING

Now the warning thrown:

Warning

Why am I seeing the warning at one place and not other. ALso, How Can I overcome this warning.

I have already tried:

foreach (JObject item in jArray)
{
   if(item != null)
   {
      clusterIds.Add(item.GetValue("value").ToString());
}}

or checking if item.values != null


Solution

  • In recent .NET versions, .ToString() is declared as string? ToString(), so it could return null.

    The difference you're seeing is because the string concatenation operator += allows a null string to be concatenated to a non-null string (it does nothing), but your clusterIds is declared as a list that cannot contain nulls, so you get the warning that you're seeing.

    To be clear, this is OK:

    string x = "x";
    x += null;
    Console.WriteLine(x);
    

    And this will give you a warning:

    List<string> y = new List<string>();
    y.Add(null);  // Not OK
    

    You can suppress the warning by adding a null-forgiving operator:

    clusterIds.Add(item.GetValue("value").ToString()!);