What is the best way to handle CS8602 "may be null here" warnings which are not accurate?

Viewed 62

MRE on dotNetFiddle

In the following example, I get warning CS8602 in method Print(). I am unsure why because it seem to me static analysis would show that Print is only ever called after Prepare - and as it's a private method it can't be called any other way, therefore owould always be non-null when accessed.

I've been impressed how clever the compiler is at telling when a nullable reference variable is definitely not null even in quite complex code logic so is this a limitation in the compiler or a misunderstanding on my part?

What should I do about it? Suppressing the warning seems like a code smell to me, but testing for null seems like paranoid coding.

using System;

#nullable enable
public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
        var p = new Program();
        p.Go();
    }
    
    object? o;
    public void Go()
    {
        Prepare();
        Print();
    }
    
    private void Prepare()
    {
        o = "Test String";
    }
    private void Print()
    {
        Console.WriteLine(o.ToString()); //dereference of a possibly null reference
    }
}
0 Answers
Related