Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Practical usage of params indexer

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?

like image 726
Yeldar Kurmangaliyev Avatar asked Nov 10 '22 00:11

Yeldar Kurmangaliyev


1 Answers

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.

like image 154
Yeldar Kurmangaliyev Avatar answered Nov 14 '22 21:11

Yeldar Kurmangaliyev