Enforcing C# 7’s code style & latest coding patterns using EditorConfig in Visual Studio 2017

EditorConfig for enforcing code style

EditorConfig can be used to define and maintain consistent coding styles in Visual Studio 2017. You don’t need to install any plugins in VS 2017 to use EditorConfig. VS 2017 comes bundled with native support for EditorConfig.

All you need to add “.editorconfig” file into your VS Solution.

editorconfig VS 2017 - add to solution

For topmost .editorconfig file, you need to set root = true.  As shown in sample .editorconfig file shown below:

You can even override it at individual project level.

editorconfig override VS 2017

For child directories’s .editorconfig files, you need to set root = false.  As shown in sample .editorconfig file shown below:

Format for defining rules for language conventions in EditorConfig in VS 2017

options_name = false|true : none|suggestion|warning|error

Some examples:

1.  dotnet_style_predefined_type_for_locals_parameters_members:

If we have the following rule defined in .editorconfig file:

The below code will give “Name can be simplified” warning:

editorconfig vs 2017 rule dotnet_style_predefined_type_for_locals_parameters_members

2.  csharp_style_pattern_matching_over_is_with_cast_check:

If we have the following rule defined in .editorconfig file:

The below code will give “Use pattern matching” error:

editorconfig VS 2017 - use pattern matching - csharp_style_pattern_matching_over_is_with_cast_check rule

3.  csharp_style_inlined_variable_declaration:

If we have the following rule defined in .editorconfig file:

The below code will give “Variable declaration can be inlined” error:

editorconfig VS 2017 - variable decalaration can be inlined - csharp_style_inlined_variable_declaration rule

4.  csharp_style_var_for_built_in_types:

If we have the following rule defined in .editorconfig file:

The below code will give “Use explicit type instead of ‘var'” warning:

editorconfig VS 2017 - explicit type over var for built-in types - csharp_style_var_for_built_in_types rule

5.  csharp_style_expression_bodied_constructors:

If we have the following rule defined in .editorconfig file:

The below code will give “Use expression body for constructors” error:

editorconfig VS 2017 - expression bodied constructor - csharp_style_expression_bodied_constructors rule

Format for defining rules for formatting conventions in EditorConfig in VS 2017

rule_name = false|true

Example:

dotnet_sort_system_directives_first:

Following rule defined in .editorconfig file:

Enforcing C# 7’s code style & patterns using EditorConfig in VS 2017

Final EditorConfig file that I have setup:

Happy Coding !!!

Kapil Khandelwal

Web Developer, Blogger, Microsoft Certified Professional (MCP), DZone’s Most Valuable Blogger (MVB)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *