Daniel
Daniel

Reputation: 47904

Read-only vs auto (read-only) property

Is there a difference between using a read-only property:

type T(arg) =
  member x.M = arg

and using an automatically implemented property:

type T(arg) =
  member val M = arg

assuming arg has no side effects? Any reason to prefer one over the other?

Upvotes: 7

Views: 1018

Answers (1)

Be Brave Be Like Ukraine
Be Brave Be Like Ukraine

Reputation: 7735

The essential difference between those is that member val represents an expression that is computed only once during instance initialization. Therefore,

type Person(fname, lname) =
  member val Name = fname + lname // would be calculated once

So, the first consideration is performance.

Another consideration is based on two limitations of auto properties:

  • you can only use them in types with primary ctor;
  • they can't be virtual

Upvotes: 12

Related Questions