Warm tip: This article is reproduced from stackoverflow.com, please click
f#

Create record instance with default values

发布于 2020-04-17 12:28:39

I have a record type:

type Person = 
   {
       Name : string
       Age : int
   }

And I need a function which returns new instances of this record with default (in C# point of view) fields.

I can do it like this:

let f = 
  {
     Name = ""
     Age = 0
  }

but I would like to avoid all fields enumeration and use something like this:

let f = new Person

Is there any way to do it ?

Questioner
demas
Viewed
67
John Palmer 2015-03-01 14:27

Used unchecked.DefaultOf<'t>. However be aware that F# records are immutable, so this is probably not what you want.