Search code examples
c#wpfnullwarnings

Possible null reference after null check


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();
}

Solution

  • 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() ?? "";