Skip to content

Commit

Permalink
Fixed issue with TypeConverter<T> where T is Nullable did not w…
Browse files Browse the repository at this point in the history
…ork.
  • Loading branch information
JoshClose committed Apr 3, 2024
1 parent 8599e80 commit 9a7f093
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 6 deletions.
7 changes: 1 addition & 6 deletions src/CsvHelper/TypeConversion/TypeConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,6 @@ public abstract class TypeConverter<T> : 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);
}
}
45 changes: 45 additions & 0 deletions tests/CsvHelper.Tests/TypeConversion/TypeConverter`1Tests.cs
Original file line number Diff line number Diff line change
@@ -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<bool?>
{
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() ?? "";
}
}
}
}

0 comments on commit 9a7f093

Please sign in to comment.