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.
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.)
See more on this question at Stackoverflow