Aria Bounds
Aria Bounds

Reputation: 163

How do you prevent possible null reference warnings for custom TryParse methods?

Take a method like this for example:

public static bool TryParse(string input, out Tuple<TimeSpan, TimeSpan>? timeSpanPair)
{
    // conversion code here
}

It follows the "Try" pattern, but how do you make it so you do not get a potential null reference warning when using it?

if(TryParse("test data", out var output)
{
   Console.WriteLine(output.ToString()); // possible null reference!
}
else
{
   Console.WriteLine("there was an error!");
}

I stumbled across this answer by accident after a bit of searching, so I decided to post an answer for it to make it easier to find. Hope it can help someone!

Upvotes: 3

Views: 553

Answers (1)

Aria Bounds
Aria Bounds

Reputation: 163

If you use the NotNullWhenAttribute you can define when the value will not be null, even if it is marked as nullable.

For example:

using System.Diagnostics.CodeAnalysis;

...

public static bool TryParse(string input, [NotNullWhen(true)] out Tuple<TimeSpan, TimeSpan>? timeSpanPair)
{
    // conversion code here
}

And then your result will no longer give you possible null reference messages if it is wrapped in an if statement!

Upvotes: 4

Related Questions