SA1413: Use trailing comma in multi-line initializers and lists
📝 This rule is new for StyleCop Analyzers, and was not present in StyleCop Classic.
Cause
The last item in a multi-line C# initializer, enum declaration, switch expression, property pattern, or collection expression is missing a trailing comma.
Rationale
This rule is specifically designed to work well with the most widely used source control systems as an aid to long-term code review. By placing a comma on the last line of a multi-line sequence, developers who append an item to the list or reorder the list at some point in the future will not need to modify any more lines than absolutely necessary for the change. As a result, the size of the subsequent code review is minimized and focused, and tools like git blame continue to show the original author and commit for the item that was previously last in the list.
Rule description
A violation of this rule occurs when the last statement of a C# initializer or list is missing a trailing comma.
For example, the following code would generate one instance of this violation:
var x = new Barnacle
{
Age = 100,
Height = 0.2M,
Weight = 0.88M
};
The following code would not produce any violations:
var x = new Barnacle
{
Age = 100,
Height = 0.2M,
Weight = 0.88M,
};
The rule covers object, collection, array, and with initializers, anonymous object creation expressions, and enum
members. Starting with C# 8.0, it also applies to switch expression arms and the subpatterns inside multi-line property
patterns. Starting with C# 12, it also applies to the elements of multi-line collection expressions. Add a trailing comma
to the last arm, subpattern, or element when they span multiple lines.
How to fix violations
To fix a violation of this rule, add a trailing comma to the last statement in the initializer.
How to suppress violations
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1413:UseTrailingCommasInMultiLineInitializers", Justification = "Reviewed.")]
#pragma warning disable SA1413 // UseTrailingCommasInMultiLineInitializers
#pragma warning restore SA1413 // UseTrailingCommasInMultiLineInitializers