Table of Contents

SA1312: Variable names should begin with lower-case letter

📝 This rule is new for StyleCop Analyzers, and was not present in StyleCop Classic.

Cause

The name of a variable in C# does not begin with a lower-case letter.

Rule description

A violation of this rule occurs when the name of a variable does not begin with a lower-case letter.

If the variable name is intended to match the name of an item associated with Win32 or COM, and thus needs to begin with an upper-case letter, place the variable 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.

Names made only of underscores (such as _ or __) are allowed for foreach iteration variables and C# 8 using declarations, since a discard cannot be used in those places. Elsewhere, a discard should be used instead of a variable named _. For example, write _ = GetValue(); rather than var _ = GetValue();.

How to fix violations

To fix a violation of this rule, change the name of the variable so that it begins with a lower-case letter, or place the item within a NativeMethods class if appropriate.

When a variable whose name is made only of underscores is never used, the code fix can replace it with a discard (C# 7 and later). For example:

Before After
var _ = GetValue(); _ = GetValue();
string __ = GetValue(); _ = GetValue();
int.TryParse(text, out var __); int.TryParse(text, out _);
int.TryParse(text, out int __); int.TryParse(text, out int _);
var (__, value) = GetPair(); var (_, value) = GetPair();
if (obj is int __) if (obj is int _)

This code fix is not offered when the variable is read or written elsewhere, when a declaration declares more than one variable or has no initializer, when changing it to a discard would change which conversion is applied to the value (for example long __ = 1;, string __ = null;, or a user-defined implicit conversion), or when another symbol named _ is in scope and the discard would bind to that symbol instead. If another symbol named _ is in scope, out var __ becomes out var _ rather than out _.

How to suppress violations

#pragma warning disable SA1312 // VariableNamesMustBeginWithLowerCaseLetter
int Variable = 3;
#pragma warning restore SA1312 // VariableNamesMustBeginWithLowerCaseLetter