Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# class property vs explicit fields

Tags:

.net

f#

Can anyone help me with example on when an explicit field is necessary in F#? for instance, how would the following three classes be all useful

type MyClass =
    val a : int
    val b : int
    new(a0, b0) = { a = a0; b = b0; }

or

type MyClass() =
    [<DefaultValue>] val mutable a: int
    [<DefaultValue>] val mutable b: int
    member this.Setab( a0: int, b0: int) =
       a<- a0
       b<- b0

comparing with

type MyClass(a0:int,b0:int) =
    member x.a = a0
    member x.b = b0

I can only understand the last class. thanks.

EDIT: the following question is an example that the first two notions are necessary: Order of fields in a type for FileHelpers

like image 772
ahala Avatar asked Dec 12 '25 17:12

ahala


1 Answers

The first two forms have some limited uses, they are useful if you need to be very explicity about the way the fields in a class are laid out. For example you maybe passing the type to unmanaged code which expects a certain number of fields in a certain or order, or you maybe passing it to an api that uses reflection over the fields.

like image 164
Robert Avatar answered Dec 14 '25 08:12

Robert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!