Search code examples
c#csvhelper

CsvHelper library in C#, nulls as empty string


I am trying to use CsvHelper library to write records (or list<SomeModel>) to CSV, but SomeModel class has some reference types properties that are sometimes null. I am wondering is there a way to print nulls as empty string instead of "null". I can see that CsvWriter.WriteRecords method is virtual so I can extend the class and create a custom implementation of it but there should be an easier way or some confirguration.


Solution

  • You can simply set this attribute

    csv.Configuration.UseNewObjectForNullReferenceMembers = true;
    

    it'll simply create a new object if a null reference is found. In the ctor of the object class, assign empty string as default.