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

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

Barbara Streisand
Barbara StreisandOriginal
2025-01-07 07:12:43256browse

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

Overloading the Square-Bracket Operator in C#

In many .NET classes, such as the DataGridView, you can access elements using the square-bracket operator:

DataGridView dgv = ...;
DataGridViewCell cell = dgv[1, 5];

This documentation provides insights into the implementation and behavior of this operator.

Relevant Documentation

The documentation for the square-bracket operator is found under the Item property.

How to Overload

To overload the square-bracket operator, define a property as follows:

public object this[int x, int y] { get {...}; set {...} };

Exception Handling

The indexer in DataGridView does not throw an exception when invalid coordinates are supplied. However, it is important to note that this may not be the case for all indexers.

Example Implementation

The following example demonstrates overloading the square-bracket operator in a custom class:

public class MyClass
{
    private List<object> _innerList;

    public MyClass()
    {
        _innerList = new List<object>();
    }

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

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