10

I've seen this kind of property declaration in a .NET 4.6.1 C# project

public object MyObject => new object();

I'm used to declaring read only properties like this:

public object MyObject { get; }

I understand that there are some differences between the two (the first one creates a new object), but I would like a deeper explanation as well as some indications of when to use either of them.

bwegs
  • 3,769
  • 2
  • 30
  • 33
Karoline Brynildsen
  • 3,598
  • 6
  • 35
  • 45

2 Answers2

16

The first uses the new-to-C#-6 expression-bodied member syntax. It's equivalent to:

public object MyObject
{
    get { return new object(); }
}

The second is also new to C# 6 - an automatically implemented read-only property. It's equivalent to:

private readonly object _myObject; // Except using an unspeakable name
public object MyObject
{
    get { return _myObject; }
}

You can only assign to MyObject from within a constructor in the declaring class, which actually just assigns to the field instead.

(Both of these "equivalencies" are using old-school property declarations, where you always have get, set or both as blocks containing code.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 2
    Its a shame the highest scoring member of SO doesn't leap to the "its a duplicate" option. – Meirion Hughes Feb 18 '16 at 13:16
  • 3
    @MeirionHughes: Well, in this case this question is specifically asking about the difference between an automatically implemented read-only property and an expression-bodied member property. The duplicate does not ask about that. I can see it either way. – Jon Skeet Feb 18 '16 at 13:19
  • Should you not also reopen then? You have the reputation to do so single-handedly. – Meirion Hughes Feb 18 '16 at 13:59
  • 1
    @MeirionHughes: I could: but I'm sufficiently uncertain either way as to wish to do anything single-handedly. If others want to close it as a dupe, that's fine by me. If others want to reopen it, that's fine by me. – Jon Skeet Feb 18 '16 at 14:05
3

C# 6 evaluates the expression on the right of the arrow function every time you call the property getter.

In your case, you'd instantiate a new object() every time.

In the other case, it would read from the backing field of the property.

MichaC
  • 13,104
  • 2
  • 44
  • 56