JoshClose / CsvHelper

Library to help reading and writing CSV files
http://joshclose.github.io/CsvHelper/
Other
4.75k stars 1.06k forks source link

Nullability - TryGet dereference of a possibly null reference #2058

Open dotTrench opened 2 years ago

dotTrench commented 2 years ago

Describe the bug When using the TryGetField methods with nullability turned on the out field is always considered nullable regardless if the method returns true or false.

To Reproduce

var csvReader = CreateCsvReader();
if (csvReader.TryGetField<string>("MyField", out var data))
{
    var mySubstring = data.Substring(0, 10); // [CS8602] Dereference of a possibly null reference.
}

Expected behavior if the return value from TryGetField returns true the out field shouldn't be considered nullable.

Additional context I assume this can be achieved by adding the NotNullWhenAttribute to the TryRead methods in IReaderRow and CsvReader methods for frameworks where nullability is enabled e.g.

bool TryGetField<T>(string column, [NotNullWhen(true)] out T? field);
JoshClose commented 2 years ago

Oh interesting. I'm sure there are a lot of places I'll need to do this. I have nullable stuff partially in place. Takes a while to do retroactively though.