-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Description
Describe the bug
When using .Constant in a mapper with decimal or some of the floating point types, the ObjectRecordWriter uses the threads/systems current culture instead of the culture provided in a CsvConfiguration.
To Reproduce
Here is an example showing the problem. The Income output uses a , (comma) as a decimal separator but the constant value uses the .. Currently the constants use the threads/application CurrentCulture and not the one from the CsvConfiguration.
using System.Globalization;
using CsvHelper;
using CsvHelper.Configuration;
var enCulture = new CultureInfo("en-US");
CultureInfo.CurrentCulture = enCulture;
var culture = new CultureInfo("de-DE");
var config = new CsvConfiguration(culture)
{
HasHeaderRecord = false,
};
using var writer = new StringWriter();
using var csv = new CsvWriter(writer, config, false);
csv.Context.RegisterClassMap<PersonMap>();
Person[] persons = [ new Person(3.14m), ];
csv.WriteRecords(persons);
writer.Flush();
var result = writer.ToString();
Console.WriteLine(result); // result in 3,14;3.1415
public sealed record class Person(decimal Income);
public sealed class PersonMap : ClassMap<Person>
{
public PersonMap()
{
Map(m => m.Income).Name("Income");
Map().Name("Decimal").Constant(3.1415m);
}
}
Expected behavior
Both, the Income and the constant value should use the same decimal separator as it is defined in the CultureInfo provided to the CsvConfiguration.
Workaround
You can solve this by specifying the culture for each constant mapping.
Map().Name("Decimal").Constant(3.1415m).TypeConverterOption.CultureInfo(cultureInfo);
Additional context
I am not sure if this is really a bug or an intentional design choice. Changing it now may break some existing code relying on this behaviour.