Skip to content

Mapping of Constant do not use the culture specified in a CsvConfiguration on writes #2358

@guwi-smartpoint

Description

@guwi-smartpoint

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.

Screenshots
Image

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions