1

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?

Sun
  • 4,458
  • 14
  • 66
  • 108
  • The compiler is warning you about you could return a null value at run time. The null-forgiving operator has no effect at run time. It only affects the compiler's static flow analysis. – ɐsɹǝʌ ǝɔıʌ Jan 18 '22 at 17:15
  • Hi there, I understand it has no effect at runtime. But I thought the point of using the null-forgiving operator was for me to tell the compiler that I know the value will never be null so suppress the warning? If not, how can I suppress the warning? – Sun Jan 18 '22 at 17:19
  • 2
    Note that `object.ToString` returns `string?`, so really you should be returning `string?` to match that. – juharr Jan 18 '22 at 17:48
  • 2
    @Sun You told to compiler that Value is not null, but ToString can return null – Lazar Đorđević Jan 18 '22 at 17:48
  • 1
    @Sun there is a full analysis of how the compiler behaves in Jon Skeet's answer to this question https://stackoverflow.com/questions/59306751/why-does-this-code-give-a-possible-null-reference-return-compiler-warning – Elham Kohestani Jan 18 '22 at 17:56

1 Answers1

2

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; }
Moho
  • 15,457
  • 1
  • 30
  • 31