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
Release: 2025-01-07 07:12:43
Original
256 people have browsed it

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];
Copy after login

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 {...} };
Copy after login

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; }
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template