5

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?

Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
  • 3
    I have to admit: that's a pretty funky use case for the `params` keyword. – Kirill Shlenskiy Dec 08 '15 at 09:08
  • An indexer is just syntactic sugar applied to a normal method (with an enforcement that it has at least one parameter). Since a normal method takes a *formal-parameter-list* (defined in section 10.6.1 of the C# language specification) and a *formal-parameter-list* may include a *parameter-array*, it means you can use `params` with an indexer. – Matthew Watson Dec 08 '15 at 09:30

1 Answers1

1

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.

Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
  • 1
    I guess that since indexers are translated into methods in IL it's not surprising that you can facilitate `params` keyword. There is one difference to methods though - while you can call a method completely omitting the arguments (the parameter array is then "autoamagically" instantiated as an empty array), you cannot call an indexer without any argument. – Grx70 Dec 08 '15 at 09:22