Search code examples
c#c#-8.0nullable-reference-types

Null-Forgiving operator still showing warning


I have the following method to override ToString()

    public override string ToString()
    {
        if (HasNoValue)
            return "No value";

        return Value!.ToString();
    }

If HasNoValue returns true, the value property contains null so "No Value" is returned.

The HasNoValue property (and HasValue) looks like this:

public bool HasValue => value != null;

public bool HasNoValue => !HasValue;

So if NoHasValue is false I know value is not Null. As you can see I've added the null-forgiving operator on the value property before the call to ToString()

I have Nullable enable within my project <Nullable>enable</Nullable>

However, I still receive the following warning:

Warning CS8603 Possible null reference return.

Why am I receiving this warning if I've added the null-forgiving operator?


Solution

  • The direct answer to your question is that Object.ToString() returns string?, so you need the null-forgiving operator at the end of the .ToString() call

    You can use the MemberNotNullWhen attribute to tell the compiler that the Value property won't be null when the HasNoValue property is false

    [MemberNotNullWhen(false, nameof(HasNoValue))]
    public object? Value { get; set; }