How Indexers Are Implemented

Even though the CLR has the notion of indexed properties, which are properties that accept parameters, C# doesn’t fully expose this feature. Only in COM interop scenarios (the subject of Chapter 22) and starting from C# 4.0, indexed properties can be consumed in limited scenarios. One key problem with generalized use of indexed properties is the multiple meanings the following piece of code could have:

employees.Numbers["Bart"];

Does this mean we can obtain an object called numbers that we subsequently are indexing into, or does it mean that there’s an indexed property called Numbers that does accept a string as its parameter?

Indexers as they’re known in C# are a special indexed property of which only a single one ...

Get C# 4.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.