Skip to content

Conversation

SteveGuoh
Copy link

Fixes #2141

✅ Problem

This PR resolves the issue where attributes like [Format], [Constant], and [Default] have no effect when applied to parameters in positional record constructors, particularly during WriteRecords() operations.

🔍 Original Issue Example (from #2141)

Given the following record:

public record Person(string Name, [Format("yyyy-MM-dd")] DateTime Birthday);

And the following code:

var records = new List<Person>
{
    new("Alice", new DateTime(1990, 2, 1))
};

using var writer = new StringWriter();
using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);
csv.WriteRecords(records);

Console.WriteLine(writer.ToString());

❌ Actual Output (Before Fix)

Name,Birthday
Alice,2/1/1990 12:00:00 AM

✅ Expected Output (After Fix)

Name,Birthday
Alice,1990-02-01

🛠️ Changes

  • Ensures that mapping attributes applied to record constructor parameters are copied to their corresponding member maps during auto-mapping.
  • Enables support for write-related attributes (FormatAttribute, ConstantAttribute, DefaultAttribute, etc.) on positional record constructor parameters.

✅ Tests

  • Added unit tests to verify reading and writing of records with attributes applied to constructor parameters.

📦 Impact

  • This enhancement improves CsvHelper's support for C# 9+ positional records.
  • Allows developers to rely on attribute-based mapping even for simplified record types, reducing the need for verbose ClassMap definitions in many scenarios.

…ord constructor parameters and field-style records (JoshClose#2141)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant