From 9a7f0934633687f8ec58b58b5d81cb69633c541c Mon Sep 17 00:00:00 2001 From: Josh Close Date: Wed, 3 Apr 2024 12:08:38 -0500 Subject: [PATCH] Fixed issue with `TypeConverter` where `T` is `Nullable` did not work. --- src/CsvHelper/TypeConversion/TypeConverter.cs | 7 +-- .../TypeConversion/TypeConverter`1Tests.cs | 45 +++++++++++++++++++ 2 files changed, 46 insertions(+), 6 deletions(-) create mode 100644 tests/CsvHelper.Tests/TypeConversion/TypeConverter`1Tests.cs diff --git a/src/CsvHelper/TypeConversion/TypeConverter.cs b/src/CsvHelper/TypeConversion/TypeConverter.cs index 238175d14..0d591dadb 100644 --- a/src/CsvHelper/TypeConversion/TypeConverter.cs +++ b/src/CsvHelper/TypeConversion/TypeConverter.cs @@ -32,11 +32,6 @@ public abstract class TypeConverter : ITypeConverter object ITypeConverter.ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData) => ConvertFromString(text, row, memberMapData); - string ITypeConverter.ConvertToString(object value, IWriterRow row, MemberMapData memberMapData) - { - return value is T v - ? ConvertToString(v, row, memberMapData) - : throw new InvalidCastException(); - } + string ITypeConverter.ConvertToString(object value, IWriterRow row, MemberMapData memberMapData) => ConvertToString((T)value, row, memberMapData); } } diff --git a/tests/CsvHelper.Tests/TypeConversion/TypeConverter`1Tests.cs b/tests/CsvHelper.Tests/TypeConversion/TypeConverter`1Tests.cs new file mode 100644 index 000000000..f8a5aafa1 --- /dev/null +++ b/tests/CsvHelper.Tests/TypeConversion/TypeConverter`1Tests.cs @@ -0,0 +1,45 @@ +using CsvHelper.Configuration; +using CsvHelper.TypeConversion; +using Xunit; + +namespace CsvHelper.Tests.TypeConversion +{ + public class TypeConverter1Tests + { + [Fact] + public void ConvertToString_NullableBoolean_Converts() + { + ITypeConverter converter = new GenericBoolConverter(); + var result = converter.ConvertToString(null, null, null); + + Assert.Equal(string.Empty, result); + } + + [Fact] + public void ConvertFromString_NullableBoolean_Converts() + { + ITypeConverter converter = new GenericBoolConverter(); + var result = (bool?)converter.ConvertFromString("true", null, null); + + Assert.True(result); + } + + private class GenericBoolConverter : TypeConverter + { + public override bool? ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData) + { + if (bool.TryParse(text, out var result)) + { + return result; + } + + return null; + } + + public override string ConvertToString(bool? value, IWriterRow row, MemberMapData memberMapData) + { + return value?.ToString() ?? ""; + } + } + } +}