Редактиране

Споделяне чрез


CA1043: Use integral or string argument for indexers

Property Value
Rule ID CA1043
Title Use integral or string argument for indexers
Category Design
Fix is breaking or non-breaking Breaking
Enabled by default in .NET 8 No

Cause

A type contains an indexer that uses an index type other than System.Int32, System.Int64, System.Object, or System.String.

By default, this rule only looks at externally visible types, but this is configurable.

Rule description

Indexers, that is, indexed properties, should use integer or string types for the index. These types are typically used for indexing data structures and increase the usability of the library. Use of the Object type should be restricted to those cases where the specific integer or string type cannot be specified at design time. If the design requires other types for the index, reconsider whether the type represents a logical data store. If it does not represent a logical data store, use a method.

How to fix violations

To fix a violation of this rule, change the index to an integer or string type or use a method instead of the indexer.

When to suppress warnings

Suppress a warning from this rule only after carefully considering the need for the nonstandard indexer.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable CA1043
// The code that's violating the rule is on this line.
#pragma warning restore CA1043

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.CA1043.severity = none

For more information, see How to suppress code analysis warnings.

Configure code to analyze

Use the following option to configure which parts of your codebase to run this rule on.

You can configure this option for just this rule, for all rules it applies to, or for all rules in this category (Design) that it applies to. For more information, see Code quality rule configuration options.

Include specific API surfaces

You can configure which parts of your codebase to run this rule on, based on their accessibility. For example, to specify that the rule should run only against the non-public API surface, add the following key-value pair to an .editorconfig file in your project:

dotnet_code_quality.CAXXXX.api_surface = private, internal

Example

The following example shows an indexer that uses an Int32 index.

string[] Month = new string[] { "Jan", "Feb", "..." };

public string this[int index]
{
    get => Month[index];
}
Private month() As String = {"Jan", "Feb", "..."}

Default ReadOnly Property Item(index As Integer) As String
    Get
        Return month(index)
    End Get
End Property