Home > Software engineering >  Possible null reference after null check
Possible null reference after null check

Time:08-22

I have a problem resolving this CS8603 warning. Even though there is a null-check for resource variable, null reference is still possible. How come?

enter image description here

Code:

public string GetResource(string resourcePath)
{
    var resource = Application.Current.Resources[resourcePath];
    if (resource == null)
    {
        return $"{ResourceError} [{resourcePath}]";
    }

    // ToDo: CS8603
    return resource.ToString();
}

CodePudding user response:

You did correctly check wether resource is null. But even if it is not, ToString() might return null. You can use something like

return resource.ToString() ?? "";
  • Related