Practical use of the parameter indexer

I recently discovered that an indexer can take 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 can:

 var sd = new SuperDictionary<string, object>(); /* Add values */ var res = sd["a", "b"]; 

However, I have never seen such use in the .NET Framework or any third-party libraries. Why was this implemented? What is the practical use of the introduction of the params indexer?

+5
source share
1 answer

The answer was found a minute after posting the question and viewing the code and documentation - C # allows you to use any type as a parameter for the indexer, but not params as a special case.

According to MSDN ,

Indexers do not have to be indexed by an integer value; It’s up to you how to determine the specific search engine.

In other words, an indexer can be of any type. It could be an array ...

 public IEnumerable<TValue> this[TKey[] keys] { get { return keys.Select(key => Dict[key]); } } var res = sd[new [] {"a", "b"}]; 

or any other unusual type or collection, including an array of params , if it seems convenient and appropriate in your case.

+1
source

Source: https://habr.com/ru/post/1237635/


All Articles