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!
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With