CA1043: Use integral or string argument for indexers

Note

This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

Item Value
TypeName UseIntegralOrStringArgumentForIndexers
CheckId CA1043
Category Microsoft.Design
Breaking Change Breaking

Cause

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

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.

Example

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

using namespace System;

namespace DesignLibrary
{
    public ref class Months
    {
        array<String^>^ month;

    public:
        property String^ default[int]
        {
           String^ get(int index)
           {
              return month[index];
           }
           void set(int index, String^ value)
           {
              month[index] = value;
           }
        }

        Months()
        {
            month = gcnew array<String^>(12);
            month[0] = "Jan";
            month[1] = "Feb";
            //...;
        }
    };
}
using System;

namespace DesignLibrary
{
    public class Months
    {
        string[] month = new string[] {"Jan", "Feb", "..."};

        public string this[int index]
        {
            get
            {
                return month[index];
            }
        }
    }
}
Imports System

Namespace DesignLibrary

    Public Class Months

        Private month() As String = {"Jan", "Feb", "..."}

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

    End Class

End Namespace

CA1023: Indexers should not be multidimensional

CA1024: Use properties where appropriate