Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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!

like image 954
Aria Bounds Avatar asked Sep 12 '25 00:09

Aria Bounds


1 Answers

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!

like image 62
Aria Bounds Avatar answered Sep 13 '25 15:09

Aria Bounds