CsvHelper set default custom TypeConverter

yelliver picture yelliver · Feb 9, 2017 · Viewed 9k times · Source

With CsvHelper, when I want a custom parser (for example, I want a MyBooleanConverter with the input string is "f" will be false, "t" will be "true"). But with every class I have to write mapper:

public sealed class MyClassMap : CsvClassMap<MyClass>
{
    public MyClassMap()
    {
        Map( m => m.Id ).Index( 0 ).TypeConverter<MyBooleanConverter>();
    }
}

Or

[CsvHelper.TypeConversion.TypeConverter( typeof( MyBooleanConverter) )]
public Boolean MyObjectProperty { get; set; }

How can I set MyBooleanConverter as default for every boolean field and every Class?

Answer

Michael Richardson picture Michael Richardson · Mar 4, 2017

The CsvHelper library exposes a static TypeConverterFactory. You can simply remove the default Boolean converter and add your custom converter to replace it.

TypeConverterFactory.RemoveConverter<bool>();
TypeConverterFactory.AddConverter<bool>(new MyBooleanConverter());