Home > Back-end >  Make the Intellisense nullability warning conditional, similar to Dictionary<string, string>.T
Make the Intellisense nullability warning conditional, similar to Dictionary<string, string>.T

Time:09-27

In Visual Studio, Intellisense is smart enough to know that the 'out' variable value in Dictionary<string, string>.TryGetValue(string key, out string value) is not null if the method returns true:

enter image description here

I'm trying to emulate this with the following example, but I don't know what to do. How can I give Intellisense the hint that the out variable result in TryGetString() will not be null if the method returns true?

Note: I still want the nullability check to appear when the TryGetString() method returns false, the same way it works with Dictionary<string, string>.TryGetValue(string key, out string value)

public class TestClass
{
    private int Number = 3;
    private bool TryGetString(out string? result)
    {
        // 'result' is null if this method returns 'false'
        if (Number > -1)
        {
            result = Number.ToString();
            return true;
        }
        result = null;
        return false;
    }
    public void Init()
    {
        if (TryGetString(out var result))
        {
            string a = result; // Visual Studio gives a null warning here,
                               // even though 'result' is not null inside
                               // this code block.
        }
    }
}

CodePudding user response:

There are a number of attributes in the System.Diagnostics.CodeAnalysis namespace that can be used to provide information to the compiler's code analyzer.

To indicate that an out parameter is not null when the return value is true, use the [NotNullWhen] attribute:

private bool TryGetString([NotNullWhen(returnValue: true)] out string? result)
  • Related