JoshClose / CsvHelper

Library to help reading and writing CSV files
http://joshclose.github.io/CsvHelper/
Other
4.65k stars 1.05k forks source link

Custom Type Converter page should include an example of using type converter constructor arguments #2213

Open Will-at-FreedomDev opened 7 months ago

Will-at-FreedomDev commented 7 months ago

Page: https://joshclose.github.io/CsvHelper/examples/type-conversion/custom-type-converter/

Relevant feature implementation: https://github.com/JoshClose/CsvHelper/issues/2032

Possible example:


[TypeConverter(typeof(TruncateStringConverter), 20)] // 20 is passed into the constructor of TruncateStringConverter 
public string Name { get; set; }

public class TruncateStringConverter: DefaultTypeConverter
{
    private readonly int _maxLength;

    public TruncateStringConverter(int maxLength)
    {
        _maxLength = maxLength;
    }

    public override string ConvertToString(object value, IWriterRow row, MemberMapData memberMapData)
    {
        return Truncate(value is string stringValue ? stringValue : value?.ToString());

        string Truncate(string value)
        {
            return value?[..Math.Min(value.Length, _maxLength)];
        }
    }
}
jzabroski commented 2 months ago

I did not even know this was possible. Neat.