CsvHelper icon indicating copy to clipboard operation
CsvHelper copied to clipboard

Missing separators when DefaultTypeConverter implementation returns null

Open nilvon9wo opened this issue 2 years ago • 0 comments

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

  1. Implement a DefaultTypeConverter such 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;
}
  1. Add it to an instance of CsvWriter, i.e.:
		csvWriter.Context.TypeConverterCache.AddConverter<decimal>(new CollendaDecimalConverter());
		csvWriter.Context.TypeConverterCache.AddConverter<decimal?>(new CollendaDecimalConverter());
  1. 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;
}
  1. Create some data, allowing a to sometimes be null.
  2. 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.

nilvon9wo avatar Mar 03 '23 13:03 nilvon9wo