This is based on H B's comment, but expanded a little and as a code block (making copying easier):
public interface IIndexedProperty<TValue> : IIndexedProperty<int, TValue> {}
public interface IReadOnlyIndexedProperty<out TValue> : IReadOnlyIndexedProperty<int, TValue> {}
public interface IIndexedProperty<in TIndex, TValue>
{
TValue this[TIndex index] { get; set; }
}
public interface IReadOnlyIndexedProperty<in TIndex, out TValue>
{
TValue this[TIndex index] { get; }
}
This uses covarients from C# 9.0, so if you are using an older version, strip out the in
and out
statements.
Pros:
Most common indexed properties use a simple int
index, so this allows for a simpler class / property signature if the index only needs to be an int
, but it also allows for non int
indexes.
Also provides both a read/write implementation and a read-only implementation based on your needs.
Caveat I found after trying to use this:
The shortcut for int
index only class signature. It apparently still needs the full signature for the property.
IE:
public MyClass : IIndexedProperty<string>
{
public IIndexedProperty<string> MyString => this;
string IIndexedPropety<int, string>.this[int index] { get; set; }
}