justin.m.chase
justin.m.chase

Reputation: 13665

How can I use an editorconfig to prevent underscore prefixes on fields?

I see a lot of questions about how to allow it but I would like to prevent it.

What settings would I put into my .editorconfig file to make all fields be camel_case without underscore prefixes (or any hungarian notation).

Upvotes: 3

Views: 1091

Answers (1)

ChiefTwoPencils
ChiefTwoPencils

Reputation: 13930

I was just working on the underscore rule myself. It seems making CA1707 enabled as an error doesn't cut it as it's only breaking on assemblies. I may have missed some more specs in the file but while trying to make it work I found this gist buried in a comment on this issue.

# Start of NO underscore prefix on private fields
# Define the 'private_fields' symbol group:
dotnet_naming_symbols.private_fields.applicable_kinds = field
dotnet_naming_symbols.private_fields.applicable_accessibilities = private

# Define the 'notunderscored' naming style
dotnet_naming_style.notunderscored.capitalization = camel_case
dotnet_naming_style.notunderscored.required_prefix =

# Define the 'private_fields_notunderscored' naming rule
dotnet_naming_rule.private_fields_notunderscored.symbols = private_fields
dotnet_naming_rule.private_fields_notunderscored.style = notunderscored
dotnet_naming_rule.private_fields_notunderscored.severity = error
# End of No underscore prefix on private fields

To cover all fields you'll need to update the accessibilities to:

dotnet_naming_symbols.private_fields.applicable_accessibilities = *

If you want to make it more accurate to represent all fields for all modifiers, you may prefer this version:

# Start of NO underscore prefix on all fields
# Define the 'all_fields' symbol group:
dotnet_naming_symbols.all_fields.applicable_kinds = field
dotnet_naming_symbols.all_fields.applicable_accessibilities = *

# Define the 'notunderscored' naming style
dotnet_naming_style.notunderscored.capitalization = pascal_case
dotnet_naming_style.notunderscored.required_prefix =

# Define the 'all_fields_notunderscored' naming rule
dotnet_naming_rule.all_fields_notunderscored.symbols = all_fields
dotnet_naming_rule.all_fields_notunderscored.style = notunderscored
dotnet_naming_rule.all_fields_notunderscored.severity = error
# End of No underscore prefix on all fields

Here's what you'll see for errors:

  1. _someVar = Prefix '_' is not expected
  2. someVar = These words must begin with upper case characters
  3. _SomeVar = Prefix '_' is not expected
  4. SomeVar = No error

I can't speak to the Hungarian notation part; that seems like it would be a tough one perhaps requiring a custom analyzer or using R# or StyleCop.

Upvotes: 4

Related Questions