How do I overload the square-bracket operator in C#?
Posted
by Coderer
on Stack Overflow
See other posts from Stack Overflow
or by Coderer
Published on 2008-11-13T19:20:22Z
Indexed on
2010/05/26
17:31 UTC
Read the original article
Hit count: 323
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.
© Stack Overflow or respective owner