How to: Convert Properties into the Expression-Bodied Structure
- 2 minutes to read
CodeRush can adjust the existing code to the expression body style. For example, in the Convert to Property with Backing Field refactoring.
If you use this style in features that generate new members from scratch (for example, Declaration Providers, Declare Menu, and Code Template), the new code will automatically match the expression body style. The following screencast shows the applied expression body style to the Declare Method code provider:
This example shows how to define the expression body style for properties and apply this style in code cleanup.
Follow the steps below:
Specify settings for expression bodies.
CodeRush uses the Visual Studio code style preferences and settings in the EditorConfig file for the expression body style in Visual Studio 2017 and later.
To change the settings: open Visual Studio, choose Tools | Options | Text Editor | C# | Code Style | Expression preferences, and set required options for properties and accessors. In this example, set the expression body settings for properties and accessors to “When possible”. Set settings for other members to the “Never” value.
To change the code style settings for expression bodies in Visual Studio 2015:
Open the Editor | C# | Programming Style CodeRush options page and set the expression body settings for properties and accessors.
Click Apply and OK to save these settings and close the programming style options page.
Open the Editor | C# | Code Cleanup options page, select the “Apply expression body styles” rule, and enable the “Apply in Action” option for this rule.
To apply this rule in code cleanup before a file is saved, enable the “Apply on Save” and “Apply Code Cleanup when saving a document” options for this rule.
Click Apply and OK to save these settings and close the Code Cleanup options page.
Copy the following code snippet and paste it to your project:
namespace ConsoleApp { class Sample { public string propertyName; public string StringProperty { get { return string.Empty; } } public string PropertyName { get { return propertyName; } set { propertyName = value; } } } }
Run code cleanup to apply the expression body style.
Note
You can also use the Use Expression Body refactoring to convert a property, method, constructor, destructor, getter or setter into the expression-bodied structure.