Search code examples
csvf#filehelpers

Order of fields in a type for FileHelpers


I'm reading a simple CSV file with Filehelpers - the file is just a key, value pair. (string, int64)

The f# type I've written for this is:

type MapVal (key:string, value:int64) =
    new()= MapVal("",0L)
    member x.Key = key
    member x.Value = value

I'm missing something elementary here, but FileHelpers always assumes the order of fields to be the reverse of what I've specified - as in Value, Key.

let dfe = new DelimitedFileEngine(typeof<MapVal>)
let recs = dfe.ReadFile(@"D:\e.dat")
recs |> Seq.length

What am I missing here?


Solution

  • The order of primary constructor parameters doesn't necessarily determine the order that fields occur within a type (in fact, depending on how the parameters are used, they may not even result in a field being generated). The fact that FileHelpers doesn't provide a way to use properties instead of fields is unforunate, in my opinion. If you want better control over the physical layout of the class, you'll need to declare the fields explicitly:

    type MapVal = 
        val mutable key : string
        val mutable value : int64
        new() = { key = ""; value = 0L }
        new(k, v) = { key = k; value = v }
        member x.Key = x.key
        member x.Value = x.value