How do I overload the square-bracket operator in C#?

DataGridView, for example, lets you do this:

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

but for the life of me I can’t find the documentation on the index/square-bracket operator. What do they call it? Where is it implemented? Can it throw? How can I do the same thing in my own classes?

ETA: Thanks for all the quick answers. Briefly: the relevant documentation is under the “Item” property; the way to overload is by declaring a property like public object this[int x, int y]{ get{...}; set{...} }; the indexer for DataGridView does not throw, at least according to the documentation. It doesn’t mention what happens if you supply invalid coordinates.

ETA Again: OK, even though the documentation makes no mention of it (naughty Microsoft!), it turns out that the indexer for DataGridView will in fact throw an ArgumentOutOfRangeException if you supply it with invalid coordinates. Fair warning.

8 Answers
8

Leave a Comment