8

In C# 6.0, the new syntax let us write read-only auto-properties with using an initializer:

public bool AllowsDuplicates { get; } = true;

Likewise, we can write it using an expression body getter:

public bool AllowsDuplicates => true;

For simple types, these two should have the same effect: a read-only auto-property that returns true.

But is one of them preferred over the other? I suspect that the former uses a backing field:

private readonly bool _backingField = true;
public bool AllowsDuplicates {
    get {
        return _backingField;
    }
}

Whereas the latter is turned into something like:

public bool AllowsDuplicates {
    get {
        return true;
    }
}

Is that right, or is the compiler smarter than this?

Mikkel R. Lund
  • 2,336
  • 1
  • 31
  • 44
  • The point is a little moot, as a `public const` would be more appropriate for this case. For the rest, very similar to [this recent question](http://stackoverflow.com/q/36820229/) – H H May 02 '16 at 20:50
  • @HenkHolterman No, I don't believe it is. I'm specifically asking about simple types. – Mikkel R. Lund May 03 '16 at 08:50
  • But why use properties at all for this kind of values? – H H May 03 '16 at 11:30
  • 1
    Because the property is defined in an interface ;) And moreover, you should rather expose a property than a field, since that will allow you to change it the internal implementation later on, without breaking clients code. – Mikkel R. Lund May 03 '16 at 13:13
  • So there is (might be) a tiny difference in space used, not really something you would ever notice. – H H May 03 '16 at 13:46

2 Answers2

8

I suspect that the former uses a backing field

The auto-property initializer does in fact creating a backing field! You can throw this in ILSpy and see it in the output:

public class One
{
    public bool AllowsDuplicates
    {
        [CompilerGenerated]
        get
        {
            return this.<AllowsDuplicates>k__BackingField;
        }
    }

    public One()
    {
        this.<AllowsDuplicates>k__BackingField = true;
        base..ctor();
    }
}

public class Two
{
    public bool AllowsDuplicates
    {
        get
        {
            return true;
        }
    }
}

But is one of them preferred over the other?

For the specific example in the question, the auto-property would allow a constructor to ask for a bool and assign it. The second style would not. If the intent is to use it as a "default value" which can be modified once during construction, then an auto-property is the right choice.

class Test
{
    // Could assign this in the second constructor
    public bool AllowsDuplicates { get; } = true;

    // Cannot assign this in the second constructor
    public bool AllowsDuplicates => true;

    public Test()
    {
        // Default value used
    }

    public Test(bool value)
    {
        AllowsDuplicates = value;
    }
}

I've seen expression bodied syntax win out most when it's a cover for a small function that is utilized as a property. A struct in Eric Lippert's dedoublifier has a nice example of this:

public DoubleHelper(double d)
{
    this.RawBits = (ulong)BitConverter.DoubleToInt64Bits(d);
}

public ulong RawBits { get; }
// RawSign is 1 if zero or negative, 0 if zero or positive
public int RawSign => (int)(RawBits >> 63);
public int RawExponent => (int)(RawBits >> 52) & 0x7FF;
public long RawMantissa => (long)(RawBits & 0x000FFFFFFFFFFFFF);
public bool IsNaN => RawExponent == 0x7ff && RawMantissa != 0;
public bool IsInfinity => RawExponent == 0x7ff && RawMantissa == 0;
public bool IsZero => RawExponent == 0 && RawMantissa == 0;
public bool IsDenormal => RawExponent == 0 && RawMantissa != 0;

There's one value which is assigned in the constructor, and the rest are property values which are computed based off of it.

Will Ray
  • 10,621
  • 3
  • 46
  • 61
  • The first part of you answer is right. But from "But is one of them preferred over the other?" you no longer focus on **simple types**, which the question is about. `DateTime.Now` is not a simple type; it is a property (that should have been implemented as a method) that returns a simple type. – Mikkel R. Lund May 03 '16 at 08:52
  • 1
    @MikkelR.Lund I've updated the answer to focus on the specific example in the question. – Will Ray May 03 '16 at 14:14
3

I suspect that the former uses a backing field, whereas the latter is turned into something like, Is that right?

Yes, it's like you said, Auto-property Initializer set the value of the backing field at the moment of the declaration.

And the Expression-bodied is a syntax simplification for the get body.

But is one of them preferred over the other?

Depends, if your property is more complex that just returning the same value, for example, like an Elapsed or Current property, or anything that needs to be computed an Expression-bodied is more suitable.
In an Expression-bodied you define the code to be executed each time the property is accessed.

If your property is supposed to be immutable, just an initial constant value then Auto-property Initializer would be preferred.

Arturo Menchaca
  • 15,783
  • 1
  • 29
  • 53
  • "If your property is supposed to be immutable, just an initial constant value then Auto-property Initializer would be preferred." But is this really the case, if the contant value is a simple type as in the question? – Mikkel R. Lund May 03 '16 at 08:54
  • @MikkelR.Lund: I think you can apply quite well for simple types, if your property behaves like a constant, then use auto-property initializers, but if your property need to be computed (like an Count) then Expression-Bodied is the only choice. – Arturo Menchaca May 03 '16 at 13:29