Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "=>" do in .Net C# when declaring a property? [duplicate]

Tags:

c#

.net

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.

like image 889
Karoline Brynildsen Avatar asked Feb 18 '16 13:02

Karoline Brynildsen


1 Answers

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.)

like image 68
Jon Skeet Avatar answered Sep 21 '22 14:09

Jon Skeet