Read-only auto-property for simple types: VS Expression Body Getter initializer

In C # 6.0, the new syntax allows you to write automatic read-only properties using an initializer:

public bool AllowsDuplicates { get; } = true;

Similarly, we can write it using the getter expression:

public bool AllowsDuplicates => true;

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

But is one of them preferable to the other? I suspect the first is using the support field:

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

While the latter turns into something like:

public bool AllowsDuplicates {
    get {
        return true;
    }
}

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

+4
source share
2 answers

I suspect the first one is using the support field

! ILSpy :

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;
        }
    }
}

?

- bool . . , " ", , -.

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;
    }
}

, , , . Eoub Lippert dedoublifier:

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;

, , - , .

+6

, , - : ?

, , Auto-property Initializer .

- get.

?

, , , , Elapsed Current, -, . Expression-body .
, .

, , .

+1

All Articles