Home >Backend Development >C++ >How Can I Overload the Square-Bracket Operator in C#?

How Can I Overload the Square-Bracket Operator in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-07 06:37:41432browse

How Can I Overload the Square-Bracket Operator in C#?

Overloading the Square-Bracket Operator in C

In C#, the square-bracket operator enables array access and key-value retrieval from dictionary-like objects. However, these classes do not natively support overloading the square-bracket operator. The documentation for this feature is listed under the "Item" property in the C# documentation.

Implementing the Indexer

To overload the square-bracket operator in your own classes, you can declare an indexer property. The syntax for an indexer property is:

public type this[arglist] { get; set; }

Where:

  • type is the type of value that the indexer returns.
  • arglist is a comma-separated list of parameters that specify the index of the element to be retrieved or set.

For example, to overload the square-bracket operator for a two-dimensional array, you could declare an indexer property as follows:

public object this[int x, int y]
{
    get { return array[x, y]; }
    set { array[x, y] = value; }
}

Limitations and Exceptions

It's important to note that the indexer in the DataGridView class does not throw an exception when you supply invalid coordinates. However, it is possible to override this behavior by explicitly handling exceptions in your own implementation of the indexer property.

For example, to throw an ArgumentOutOfRangeException if the supplied coordinates are invalid, you could implement the indexer property as follows:

public object this[int x, int y]
{
    get
    {
        if (x < 0 || x >= width)
        {
            throw new ArgumentOutOfRangeException("x");
        }
        if (y < 0 || y >= height)
        {
            throw new ArgumentOutOfRangeException("y");
        }

        return array[x, y];
    }

    set
    {
        if (x < 0 || x >= width)
        {
            throw new ArgumentOutOfRangeException("x");
        }
        if (y < 0 || y >= height)
        {
            throw new ArgumentOutOfRangeException("y");
        }

        array[x, y] = value;
    }
}

The above is the detailed content of How Can I Overload the Square-Bracket Operator in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn