Read only and auto property (read only)

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

type T(arg) = member xM = arg 

and using the automatically implemented property:

 type T(arg) = member val M = arg 

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

+6
source share
1 answer

The significant difference between the two is that member val represents an expression that evaluates only once during instance initialization. Consequently,

 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 use them only in types with primary ctor;
  • they cannot be virtual
+10
source

Source: https://habr.com/ru/post/921798/


All Articles