CsvHelper
CsvHelper copied to clipboard
Missing separators when DefaultTypeConverter implementation returns null
Describe the bug
We have a custom implementation of DefaultTypeConverter. When it returns null, the separator between it and the next column is missing so subsequent data is effectively shifted left into the wrong columns.
To Reproduce
- Implement a
DefaultTypeConvertersuch as:
using CsvHelper;
using CsvHelper.Configuration;
using CsvHelper.TypeConversion;
using System.Globalization;
namespace Enpal.Collenda.Client.SftpUploader.CsvConverters;
public class CollendaDecimalConverter : DefaultTypeConverter
{
public override string? ConvertToString(object? value, IWriterRow row, MemberMapData memberMapData) =>
value is not null and decimal decimalValue
? string.Format(CultureInfo.GetCultureInfo("de-DE"), "{0:0.00}", decimalValue)
: null;
}
- Add it to an instance of
CsvWriter, i.e.:
csvWriter.Context.TypeConverterCache.AddConverter<decimal>(new CollendaDecimalConverter());
csvWriter.Context.TypeConverterCache.AddConverter<decimal?>(new CollendaDecimalConverter());
- Create a model which includes nullable decimals, i.e.:
public class Example {
[Name("Foo")]
[Index(1)]
public decimal? a;
[Name("Bar")]
[Index(2)]
public string b;
}
- Create some data, allowing
ato sometimes be null. - Output a CSV.
Expected behavior There should be a comma between all values, regardless what they are or represent.
Screenshots N/A
Additional context
We were able to fix the issue by refactoring to return string.Empty instead of null, but it makes little sense for the return type to be nullable when actually returning null is apparently not expected and creates unexpected results.