I have classes
public class FooKeyedCollection : KeyedCollection<FooType,Foo>
{
}
public enum FooType
{
FooType1,
FooType2,
FooType3
}
public Foo
{
public FooType Type { get; set; }
public string Value { get; set; }
}
When I add items to my FooKeyedCollection, I can index them by FooType, but when I attempt to index them int, the int is interpretted as the FooType enum. As a result, it leads to a confusing error, i.e.
public static void main()
{
FooKeyedCollection fkc = new FooKeyedCollection();
Foo myFoo = new Foo();
myFoo.Type = FooType.FooType3;
myFoo.Value = "someValue";
foo.Add( myFoo );
Foo myFooByType = foo[FooType.FooType3];
Foo myFooByIndex = foo[0]; // <-- exception thrown here
}
The result of executing this code is an exception when attempting to retrieve the item by integer index. I hope to expose the FooKeyedCollection as part of a public API, and I want to protect the consumers of this API from this error. Is there any way that I can modify the FooKeyedCollection class to get proper behavior?
You might consider using the "new" keyword here:
public new Foo this[int index]
{
get
{
IList<Foo> self = this;
return self[index];
}
set
{
(IList<Foo>)[index] = value;
}
}
This will allow you to index by integer value. Using the enum explicitly will fall back to the KeyedCollection implementation.
Here's a helpful extension method to avoid these cases where the two indexers overlap - it also helps if the key is int
:
static class CollectionUtils
{
public static TValue GetByIndex<TKey,TValue>
(this KeyedCollection<TKey, TValue> collection, int index)
{
return collection[index];
}
}
then call fkc.GetByIndex(0)
and it will work fine. Inside the generic method it can only resolve index
to the int
indexer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With