NetXpert
NetXpert

Reputation: 649

Property/Accessor ambiguity when using Expression Body operators

Using C# (.Net 4.6), assuming this code:

public class test
{
    private bool _a = true;

    public test() { }

    public bool a => _a;
}

Is the public bool a => _a; implementation the same as:

public bool a { get => _a; }

or:

public bool a
{
    get => _a;
    set => _a = value;
}

?

Which is to say, if using the single expression body declaration on an Property/Accessor (as opposed to declaring both get and set separately) is the resulting functionality read/write, or read-only?

I tried looking through Microsoft's help (here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties) but it only mentioned expression bodies in one sentence and wasn't at all clear about the differences. 😕😣

Upvotes: 0

Views: 95

Answers (2)

Mohammed Igbal
Mohammed Igbal

Reputation: 11

public bool a => _a;

Implementation the same as:

public bool a { get => _a; }

And:

static bool _a = true;
public bool a { get; set; } = _a;

Implementation the same as:

public bool a
{
    get => _a;
    set => _a = value;
}

Upvotes: 0

Salah Akbari
Salah Akbari

Reputation: 39946

You would just have the get accessor only. So this:

public bool a => _a;

Will be evaluated to this:

public bool a
{
    get
    {
        return _a;
    }
}

You can find the intermediate steps and results of your code compilation here in SharpLap

Upvotes: 1

Related Questions