Recently, I have found out that indexer can accept an array of arguments as params
:
public class SuperDictionary<TKey, TValue>
{
public Dictionary<TKey, TValue> Dict { get; } = new Dictionary<TKey, TValue>();
public IEnumerable<TValue> this[params TKey[] keys]
{
get { return keys.Select(key => Dict[key]); }
}
}
Then, you will be able to do:
var sd = new SuperDictionary<string, object>();
/* Add values */
var res = sd["a", "b"];
However, I never met such usage in .NET Framework or any third-party libraries. Why has it been implemented? What is the practical usage of being able to introduce params
indexer?
The answer has been found in a minute after posting the question and looking through the code and documentation - C# allows you to use any type as a parameter for indexer, but not params
as a special case.
According to MSDN,
Indexers do not have to be indexed by an integer value; it is up to you how to define the specific look-up mechanism.
In other words, indexer can be of any type. It can either be an array...
public IEnumerable<TValue> this[TKey[] keys]
{
get { return keys.Select(key => Dict[key]); }
}
var res = sd[new [] {"a", "b"}];
or any kind of another unusual type or collection, including params
array, if it seems to be convenient and suitable in your case.
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