Skip to content

Commit

Permalink
Merge branch 'fix-nongeneric-has-header' of github.com:Rob-Hague/CsvH…
Browse files Browse the repository at this point in the history
…elper into Rob-Hague-fix-nongeneric-has-header
  • Loading branch information
JoshClose committed Jan 26, 2024
2 parents 644a570 + b6b6b79 commit 2758f5c
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
10 changes: 7 additions & 3 deletions src/CsvHelper/CsvWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -803,16 +803,20 @@ private bool WriteHeader<T>(IEnumerable<T> records)

private bool WriteHeader(IEnumerable records)
{
object record = null;
if (!hasHeaderRecord || hasHeaderBeenWritten)
{
return false;
}

foreach (var r in records)
{
if (r != null)
{
record = r;
return WriteHeader(r);
}
}

return WriteHeader(record);
return false;
}

private bool WriteHeader(object record)
Expand Down
32 changes: 32 additions & 0 deletions tests/CsvHelper.Tests/CsvWriterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
using System.Dynamic;
using Xunit;
using System.Threading;
using System.Collections;

namespace CsvHelper.Tests
{
Expand Down Expand Up @@ -835,6 +836,37 @@ public void WriteInternalConstructorClassTest()
}
}

[Theory]
[InlineData(false)]
[InlineData(true)]
public void WriteRecords_NonGeneric_HasHeaderRecord(bool hasHeaderRecord)
{
var confg = new CsvConfiguration(CultureInfo.InvariantCulture)
{
HasHeaderRecord = hasHeaderRecord
};

using var stringWriter = new StringWriter();
using var csvWriter = new CsvWriter(stringWriter, confg);

IEnumerable records = new object[] {
new TestSinglePropertyRecord { Name = "test" },
new TestRecord { IntColumn = 4 }
};

csvWriter.WriteRecords(records);
var csv = stringWriter.ToString();

if (hasHeaderRecord)
{
Assert.Equal("Name\r\ntest\r\n4,,,,\r\n", csv);
}
else
{
Assert.Equal("test\r\n4,,,,\r\n", csv);
}
}

private class GetOnly
{
internal GetOnly(string someParam)
Expand Down

0 comments on commit 2758f5c

Please sign in to comment.