Table of Contents

SA1305: Names should not use Hungarian notation

💡 This rule is disabled by default.

Cause

The name of a field, variable, or parameter in C# uses Hungarian notation.

Rule description

A violation of this rule occurs when Hungarian notation is used in the naming of fields, variables, or parameters. The use of Hungarian notation has become widespread in C++ code, but the trend in C# is to use longer, more descriptive names, which are not based on the type but instead describe what the item is used for.

In addition, modern code editors such as Visual Studio make it easy to identify type information for a variable, field, or parameter, typically by hovering the mouse cursor over its name. This reduces the need for Hungarian notation.

StyleCop assumes that any field, variable, or parameter name that begins with one or two lower-case letters followed by an upper-case letter is making use of Hungarian notation, and will flag a violation of this rule in each case. Parameters in overriding methods and methods which implement an interface member are not checked. Parameter names on methods annotated with [DllImport] are also not checked, since they often mirror native API parameter names. It is possible to declare certain prefixes as legal, in which case they will be ignored. For example, a variable named onExecute will appear to StyleCop to be using Hungarian notation, when in reality it is not. Thus, the on prefix should be flagged as an allowed prefix.

To configure the list of allowed prefixes, use stylecop.json like the following:

{
  "settings": {
    "namingRules": {
      "allowedHungarianPrefixes": [ "aa", "bb" ],
    },
  }
}

Adding a one or two letter prefix to this list will cause StyleCop to ignore fields, variables, or parameters which begin with this prefix.

If the field, variable, or parameter name is intended to match the name of an item associated with Win32 or COM, and thus needs to use Hungarian notation, place the item within a special NativeMethods class. A NativeMethods class is any class which contains a name ending in NativeMethods, and is intended as a placeholder for Win32 or COM wrappers. StyleCop will ignore this violation if the item is placed within a NativeMethods class.

How to fix violations

To fix a violation of this rule, remove the Hungarian notation from the field, variable, or parameter name, or place the item within a NativeMethods class if appropriate.

How to suppress violations

[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Reviewed.")]
#pragma warning disable SA1305 // FieldNamesMustNotUseHungarianNotation
#pragma warning restore SA1305 // FieldNamesMustNotUseHungarianNotation