What does "=>" in .Net C # do when declaring a property?
I saw such a property declaration in a .NET 4.6.1 C # project
public object MyObject => new object(); I use read-only properties to declare:
public object MyObject { get; } I understand that there are some differences between them (the first creates a new object), but I would like to get a deeper explanation, as well as some guidance on when to use any of them.
The first uses the syntax with the body expression new-to-C # -6. This is equivalent to:
public object MyObject { get { return new object(); } } The second is also new to C # 6 - an automatically implemented read-only property. This is equivalent to:
private readonly object _myObject; // Except using an unspeakable name public object MyObject { get { return _myObject; } } You can only assign MyObject from the constructor in the declaring class, which actually just assigns to this field.
(Both of these "equivalences" use old-school property declarations, where there is always get , set or both as blocks containing code.)
C # 6 evaluates the expression to the right of the arrow function every time you call the getter property.
In your case, you should create an instance of new object() every time.
Otherwise, it will read from the property support field.