I know, I know... Eric Lippert's answer to this kind of question is usually something like "because it wasn't worth the cost of designing, implementing, testing and documenting it".
But still, I'd like a better explanation... I was reading this blog post about new C# 4 features, and in the section about COM Interop, the following part caught my attention :
By the way, this code uses one more new feature: indexed properties (take a closer look at those square brackets after Range.) But this feature is available only for COM interop; you cannot create your own indexed properties in C# 4.0.
OK, but why ? I already knew and regretted that it wasn't possible to create indexed properties in C#, but this sentence made me think again about it. I can see several good reasons to implement it :
- the CLR supports it (for instance,
PropertyInfo.GetValuehas anindexparameter), so it's a pity we can't take advantage of it in C# - it is supported for COM interop, as shown in the article (using dynamic dispatch)
- it is implemented in VB.NET
- it is already possible to create indexers, i.e. to apply an index to the object itself, so it would probably be no big deal to extend the idea to properties, keeping the same syntax and just replacing
thiswith a property name
It would allow to write that kind of things :
public class Foo
{
private string[] _values = new string[3];
public string Values[int index]
{
get { return _values[index]; }
set { _values[index] = value; }
}
}
Currently the only workaround that I know is to create an inner class (ValuesCollection for instance) that implements an indexer, and change the Values