Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read-only vs auto (read-only) property

Tags:

f#

f#-3.0

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?

like image 606
Daniel Avatar asked Jul 31 '12 19:07

Daniel


People also ask

What are the properties of read only?

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 an Auto property C#?

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.

Why do we use readonly in C#?

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.


1 Answers

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
like image 66
bytebuster Avatar answered Nov 02 '22 23:11

bytebuster