Home > Software engineering >  I get "Possible null reference return" warning, although result is declared maybe null
I get "Possible null reference return" warning, although result is declared maybe null

Time:01-29

I am new to C#. I do not get why I still get this warning when I have marked the return type with "?". See screen shot attached.

    public Item? GetItem(Guid id)
    {
        return items.Where(item => item.Id == id).SingleOrDefault();
    }

Code and warning

CodePudding user response:

Item is a class, which can be null so you don't need to put nullbale keyword ? in that. May that is why you are getting warning. If you put nullable with non-nullable data type like int, you will not get that warning.

CodePudding user response:

  1. Item is a reference type, which are nullable, so you do not need to append a ? to the typename.

  2. The warning is possible null reference return. Marking a type as nullable does not remove the possibility of a null reference return. The return value is thus marked by the compiler as maybe-null. This is why you get the warning.

To resolve the warning, remove the nullable operator ? and if the warning persists, implement a null check into to the function.

  •  Tags:  
  • Related