Skip to content

Commit

Permalink
Merge branch 'Rob-Hague-converttostringtypearg'
Browse files Browse the repository at this point in the history
  • Loading branch information
JoshClose committed Jan 26, 2024
2 parents 3aea6a0 + c9fdeb2 commit 53a709b
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/CsvHelper/Expressions/ObjectRecordWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,9 @@ protected override Action<T> CreateWriteDelegate<T>(T record)
if (memberMap.Data.WritingConvertExpression != null)
{
// The user is providing the expression to do the conversion.
var constructor = typeof(ConvertToStringArgs<T>).GetConstructor(new Type[] { typeof(T) });
Type convertGenericType = memberMap.Data.WritingConvertExpression.Type.GenericTypeArguments[0];

var constructor = typeof(ConvertToStringArgs<>).MakeGenericType(convertGenericType).GetConstructor(new Type[] { convertGenericType });
var args = Expression.New(constructor, recordParameterConverted);
Expression exp = Expression.Invoke(memberMap.Data.WritingConvertExpression, args);
exp = Expression.Call(Expression.Constant(Writer), nameof(Writer.WriteField), null, exp);
Expand Down
46 changes: 46 additions & 0 deletions tests/CsvHelper.Tests/Issues/Issue2118.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using CsvHelper.Configuration;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Xunit;

namespace CsvHelper.Tests.Issues
{
public class Issue2118
{
[Fact]
public void Issue2118Test()
{
var records = new List<Foo>
{
new() { Bar = new HashSet<string> { "foo" } },
new() { Bar = new HashSet<string> { "bar" } },
};

string csvString;
using (var writer = new StringWriter())
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csv.Context.RegisterClassMap<FooMap>();
csv.WriteRecords(records);
csvString = writer.ToString();
}

Assert.Equal("Foo,Bar\r\nTrue,False\r\nFalse,True\r\n", csvString);
}

private class Foo
{
public HashSet<string> Bar { get; set; }
}

private sealed class FooMap : ClassMap<Foo>
{
public FooMap()
{
Map().Index(0).Name("Foo").Convert(x => (x.Value as Foo).Bar.Contains("foo") ? "True" : "False");
Map().Index(1).Name("Bar").Convert(x => (x.Value as Foo).Bar.Contains("bar") ? "True" : "False");
}
}
}
}

0 comments on commit 53a709b

Please sign in to comment.