Syntactic Archery

Something that trips me up occasionally in C# is syntactic sugar with properties. Specifically, the difference between the fat arrow (=>) and assignment (=) with properties. Here’s a quick note to help clear up any confusion.

Fat Arrow

Let’s remember, the fat arrow (=>) is a lambda expression. This generates a reference expression that can be evaluated, without conflict from prior usage. The key thing here is that the fat arrow (=>) generates new instances each time it is called. This means that modifications to reference objects won’t persist between calls to the property.

Example:

public class FatArrowProperties {

    // Using this...
    public int ValueProperty => 1;

    // Deconstructs to this:
    public int ValueProperty
    {
        get
        {
            return 1;
        }
    }

    // Using this...
    public object ReferenceProperty => new object();

    // Deconstructs to this:
    public object ReferenceProperty
    {
        get
        {
            return new object();  // New instance!
        }
    }
}

Assignment

Use of the assignment operator (=) is syntactic sugar for generation of a backing field. The backing field will be instantiated when the class instance is created and returned when the property getter is used. This means that modifications to reference objects will persist between calls to the property.

Example:

public class AssignmentProperties {

    // Using this...
    public int ValueProperty { get; } = 1;

    // Deconstructs to this:
    private readonly int _valueBackingField = 1;
    public int ValueProperty
    {
        get
        {
            return _valueBackingField;
        }
    }

    // Using this...
    public object ReferenceProperty { get; } = new object();

    // Deconstructs to this:
    private readonly object _referenceBackingField = new object();
    public object ReferenceProperty
    {
        get
        {
            return _referenceBackingField;  // Original reference!
        }
    }

}

Give it a Try

You can play around with this yourself using TryRoslin to quickly generate IL in your browser.