In the C# 6, you can can simplify implementing a property by using a getter-only auto property. For example, if I were implementing the abstract Stream
class:
public override bool CanRead { get; } = true;
However I can also write it with an expression body, also new in C# 6:
public override bool CanRead => true;
What is the difference between the two, and when should I use one or the other?
In the case you describe in our example, I used to prefer:
But today I notified that this implementation cause a memory allocation for the backing field. And so, this implementation:
bool CanRead => true;
can save 4 bytes.They are syntactic sugar for two different things. The former initializes a backing field, and sets it to the expression on the right hand side of the assignment during field initialization. The latter creates a
get
that does exactly what is in the expression.is equivalent to
This
is equivalent to
They behave differently. The first case sets the value of the property when the object is created and the field are initialized, the other case evaluates the expression every time the property's getter is invoked. In the simple case of a bool, the behavior is the same. However if the expression causes side effects, things are different. Consider this example:
Here, "0, 1, 2, 3" are printed. The static
counter
field is incremented every time the property's getter is invoked. However, with a property initializer:Then "0, 0, 1, 1" is printed because the expression is evaluated in the object's constructor.