False null reference warning

Viewed 25

I am writing some functions like this in C# along the lines of int.TryParse:

public bool TryGetSomeObject(out SomeObject? outObject) 
{
    outObject = GetSomeObject(); // maybe got null reference
    if (outObject != null) 
    {
       return true;
    }
    return false;
}

if (TryGetSomeObject(out SomeObject gotObject)) 
{
   // here all your references to gotObject are underlined as a possible null reference
   // even though we know for a fact gotObject is not null
}

My issue is I can't find a elegant way around this, you can write an additional unnecessary null check every time you call TryGetSomeObject or create a pointless empty instance of SomeObject in the function (not always possible) to return in the event of failure and remove the nullable operator on the out value.

Or maybe I should just learn to ignore the underlines in VS...

1 Answers
Related