Changing a property to expression-bodied based on ReSharper leads to error?

9.3k views Asked by At

one of my properties looks like this:

public string Name
{
 get{ return _name; }
 set { _name = value; }
}

but ReSharper is advising me to change it to:

public string Name
{
 get => _name;
 set => _name = value;
}

if I refactor like that then compilation throws error Is it not possible to have expression body in a Property ?

2

There are 2 answers

0
NtFreX On BEST ANSWER

Before c# 6 you couldn't use expression bodies in properties and had to write something like this.

public string FullName
{
    get { return string.Format("{0} {1}", FirstName, LastName); }
}

In c# 6 you can create readonly experession bodies.

public string FullName => $"{FirstName} {LastName}";

In c# 7 you got expression bodies for members like you showed.

public string Name
{
    get => _name;
    set => _name = value;
}
0
Michael Mairegger On

If you want ReSharper not to adapt this behavior you can change it:

Resharper > Options > Code Editing > C# > Code Style

and change the following property:

Code body > Properties, indexers and events from Expression body to Accessors with block body

If you just want to disable the suggestion change the notification state of the property mentioned above.