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?
Read only means that we can access the value of a property but we can't assign a value to it. When a property does not have a set accessor then it is a read only property. For example in the person class we have a Gender property that has only a get accessor and doesn't have a set accessor.
What is automatic property? Automatic property in C# is a property that has backing field generated by compiler. It saves developers from writing primitive getters and setters that just return value of backing field or assign to it.
In a field declaration, readonly indicates that assignment to the field can only occur as part of the declaration or in a constructor in the same class. A readonly field can be assigned and reassigned multiple times within the field declaration and constructor.
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:
virtual
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With