(1 item) |
|
(1 item) |
|
(5 items) |
|
(1 item) |
|
(1 item) |
|
(2 items) |
|
(2 items) |
|
(4 items) |
|
(1 item) |
|
(6 items) |
|
(2 items) |
|
(4 items) |
|
(1 item) |
|
(4 items) |
|
(2 items) |
|
(1 item) |
|
(1 item) |
|
(1 item) |
|
(1 item) |
|
(1 item) |
|
(1 item) |
|
(1 item) |
|
(1 item) |
|
(2 items) |
|
(2 items) |
|
(5 items) |
|
(3 items) |
|
(1 item) |
|
(1 item) |
|
(1 item) |
|
(3 items) |
|
(1 item) |
|
(1 item) |
|
(2 items) |
|
(8 items) |
|
(2 items) |
|
(7 items) |
|
(2 items) |
|
(2 items) |
|
(1 item) |
|
(2 items) |
|
(1 item) |
|
(2 items) |
|
(4 items) |
|
(1 item) |
|
(5 items) |
|
(1 item) |
|
(3 items) |
|
(2 items) |
|
(2 items) |
|
(8 items) |
|
(7 items) |
|
(3 items) |
|
(7 items) |
|
(6 items) |
|
(1 item) |
|
(2 items) |
|
(5 items) |
|
(5 items) |
|
(7 items) |
|
(3 items) |
|
(7 items) |
|
(16 items) |
|
(10 items) |
|
(27 items) |
|
(15 items) |
|
(15 items) |
|
(13 items) |
|
(16 items) |
|
(15 items) |
C# allows you to define an 'indexer', a special kind of property that allows an array-like syntax to be used on instances of
the class. For example, it's what lets the Hashtable
support this kind of syntax:
myHashTable["foo"] = "bar";
This client syntax is all well and good. The part that I think looks a bit curious is the syntax with which classes implement an indexer:
public string this [string x] { get { ... } set { ... } }
The use of square brackets around the parameter list makes sense, as that reflects the usage. The thing that I always
thought looked a bit peculiar was the use of the this
keyword.
The only way I was ever able to make sense of this was by guessing that at some point in its history, C# supported parameterisation of all properties. The CLR supports this, as does VB.NET, but C# today does not, with the specific exception of indexers. (Indexers are really parameterised properties with special support in certain languages.) However, it's not hard to imagine a variation on the indexer syntax that would allow you to define a parameterized property:
public string MyProperty [string x] { get { ... } set { ... } }
Given that more general usage, the use of this
to indicate the default indexer property seems much
less arbitrary. But I'd never seen any confirmation of this guess until Brad
posted this blast from the past. In passing he shows
an ancient bit of code which uses exactly the syntax I had long suspected existed once upon a time.
What's still not clear is why this was removed from the language. My guess is that the client-side syntax is arguably ambiguous:
// Is Foo a parameterised property, or a scalar property
// returning an object which has an indexer?
someObject.Foo["foo"] = "quux";
...but if anyone knows for sure I'd love a definitive answer.