Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 968
nshathish Avatar asked Oct 29 '25 12:10

nshathish


2 Answers

Before C# 6, you couldn't use expression bodies in properties:

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

In C# 6, you could create read-only expression bodies.

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

In C# 7, you can create expression bodies for members like you showed:

public string Name
{
    get => _name;
    set => _name = value;
}
like image 133
NtFreX Avatar answered Oct 31 '25 03:10

NtFreX


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.

like image 26
Michael Mairegger Avatar answered Oct 31 '25 03:10

Michael Mairegger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!