Does CsvHelper GetRecords() actually instantiate objects?

53 Views Asked by At

I am using CsvHelper to read data from .csv file.

My code :

var config = new CsvConfiguration(CultureInfo.InvariantCulture){ HasHeaderRecord = true };
using (var textreader = new StreamReader(filepath))
using (var csv = new CsvReader(textreader, CultureInfo.InvariantCulture))
{
    var records = csv.GetRecords<Vehicle>();                   
    foreach(var vehicle in records)
    {
        vehicles.Add(vehicle);
    }
}

At which moment is the object actually created ?

1

There are 1 best solutions below

1
Josh Close On

Yes, it does.

It creates a delegate using expression trees to instantiate the object based on your config and mapping settings.

As @dbc stated, GetRecords<T> returns an IEnumerable<T> that will yield records. That means only a single record is created and returned on each iteration of the IEnumerable<T>.

If you were to project the records using something like ToList(), that would create an object for every record and your entire file would be in memory.