TinyCsvParser icon indicating copy to clipboard operation
TinyCsvParser copied to clipboard

Support for immutable types

Open FrankHileman opened this issue 3 years ago • 8 comments

I realize this is out of scope in the original design, but do you have any plans to add support for a custom mapping to an immutable type? Specifically, to map to a class that has read-only properties, with the property values passed in the constructor. This means the mapping must create the instance. Thank you.

FrankHileman avatar May 19 '22 15:05 FrankHileman

Do you have an API in mind, so I can get an idea? Then we could see, what’s possible and eventually make a new major release and changes to the existing API. 🙂

bytefish avatar May 19 '22 16:05 bytefish

The only requirement for an API is that the mapping class (it must be custom) would have to call the constructor explicitly. If you use reflection, there is a complicated way to do that, but I think the simplest API would be one that allows the mapping class to extract the column values, then call the constructor, and return the instance to your infrastructure. You already have a way to extract column values (strong typing there would be bonus).

FrankHileman avatar May 19 '22 17:05 FrankHileman

Currently the CsvMapping class requires a parameter less constructor.

FrankHileman avatar May 19 '22 17:05 FrankHileman

You could make an equivalent to CsvMapping specifically for immutable types.

FrankHileman avatar May 19 '22 17:05 FrankHileman

If you want to simply extend the MapUsing API, you could have a delegate parameter that does not take the instantiated object as input, only the values. Then a null return value means failure, or if you allow value types to be constructed, a Result<TValue> structure is returned, and your base class (CsvImmutableMapping) would need to have a MapUsing method that accepts the correct delegate type (i.e., the delegate is strongly typed by its output).

FrankHileman avatar May 19 '22 17:05 FrankHileman

Sounds good! I think using records also makes a lot of sense and updating the API for it. But I cannot really promise, when I’ll be able to look at it. Any help is appreciated. 👍

bytefish avatar May 19 '22 17:05 bytefish

I had a try at this, and I believe both MapUsing and a similar syntax to the existing MapProperty methods can be interesting. Feel free to have a look at PR #85 and see if it fulfills your needs.

JoaoSeverino avatar May 21 '22 12:05 JoaoSeverino

A great PR! Please give me some time to take a look at it. :)

bytefish avatar May 21 '22 14:05 bytefish