I first tried to read a file with a record which contains a column with the value "120,000.00". I want to convert this column to a nullable decimal. Although the file originates from Switzerland, C# seems not to be okay with this format and the helper (using the de-CH CultureInfo) raised a TypeConverterException. So I removed the comma with a custom TypeConverter which solved the conversion problem. Unfortunately, I now get a ReaderException:
Unable to cast object of type 'System.String' to type 'System.Nullable`1[System.Decimal]'
Why is still an exception raised after the type conversion has succeeded? Can the behaviour be reproduced? (CsvHelper version 15.0.8, Stack trace at CsvHelper.CsvReader.d__63`1.MoveNext())
public class MyFile
{
public decimal? MyField { get; set; }
}
_
public MyFileMap : ClassMap<MyFile>
{
public MyFileMap()
{
Map(x => x.MyField).Name("My Field").TypeConverterOption.NumberStyles(System.Globalization.NumberStyles.Number).TypeConverter<DecimalStringReplacer>(); //custom replacer removes the comma
}
}
_
var records = csvReader.GetRecords<MyFile>() //csvReader uses CultureInfo "de-CH". Raises ReaderException
The problem was that I did not implement the custom converter correctly. This needs to return a nullable decimal, while my implementation (which I had just copy-pasted) returned a string.