Home >Backend Development >C++ >How Can I Overload 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.
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:
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; } }
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!