2

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?

5
  • 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. Commented Jan 18, 2022 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? Commented Jan 18, 2022 at 17:19
  • 2
    Note that object.ToString returns string?, so really you should be returning string? to match that. Commented Jan 18, 2022 at 17:48
  • 2
    @Sun You told to compiler that Value is not null, but ToString can return null Commented Jan 18, 2022 at 17:48
  • 1
    @Sun there is a full analysis of how the compiler behaves in Jon Skeet's answer to this question stackoverflow.com/questions/59306751/… Commented Jan 18, 2022 at 17:56

1 Answer 1

3

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; }
Sign up to request clarification or add additional context in comments.

2 Comments

Hi there, just tried this and I still receive the warning.
@Sun updated answer; Object.ToString() returns string?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.