Lawrence
Lawrence

Reputation: 3297

Default values for record types

Suppose I have a record type:

type CountHolder = { Counter: int}
type NameCount = { Name: string; Count: CountHolder}

I'm am looking for way to specify a default value for the Count property when deserializing either of the following json strings (using JSON.NET):

{"Name":"My Name","Count": null}
{"Name":"My Name"}

For example, my default value could be defined as

{ Counter :  0 }

If I could find an extension point in the JSON.NET serialization pipeline that would allow me to define a default value at runtime, I'm guessing that could solve my problem.

EDIT

In response to a comment suggesting that I modify my record type to make the Count field optional - I would rather not do this as my type is consumed by C# code. By making this field optional consumers of my code would be forced in to taking on a dependency on FSharp.Core.

Upvotes: 2

Views: 1328

Answers (1)

Daniel Fabian
Daniel Fabian

Reputation: 3838

You could always define NameCount thusly:

type NameCount = { Name: string; Count: CountHolder option }

And then deal with the None.

Upvotes: 1

Related Questions