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

How to Overload the Square-Bracket Operator in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-07 06:00:49302browse

How to Overload the Square-Bracket Operator in C#?

Overloading the Square-Bracket Operator in C#

The square-bracket operator allows classes in C# to provide indexed access to their members. This enables developers to create custom collections or data structures that can be accessed using array-like syntax.

Documentation

For information on overloading the square-bracket operator, refer to the documentation for the "Item" property.

Implementation

To overload the indexer, declare a property with the following syntax:

public object this[parameters] { get; set; }

Where parameters specifies the type and number of indices used to access the member.

Exception Handling

The indexer can optionally throw exceptions when an invalid index is passed. It is recommended to throw an ArgumentOutOfRangeException for invalid indices.

DataGridView Example

The indexer for DataGridView does not throw exceptions when invalid coordinates are supplied, although this is not explicitly mentioned in the documentation.

Custom Collection Example

public class MyCollection
{
    private List<int> _innerList = new List<int>();

    public object this[int i]
    {
        get { return _innerList[i]; }
        set { _innerList[i] = value; }
    }
}

This allows you to access members of MyCollection using the following syntax:

var collection = new MyCollection();
int item = collection[0];

The above is the detailed content of How to 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