Alex Rivera | Logout

Why it is not possible to define generic indexers in .NET?

Asked 2009-01-30T07:49:24.877
61

Why can't you create a generic indexer in .NET?

the following code throws a compiler error:

public T this<T>[string key]
{
    get => /* Return generic type T. */
}

Does this mean you can't create a generic indexer for a generic member collection?

Edit
Report

1 Answer

3

I like the ability to have an indexer without handing out a direct reference to the "indexed" item. I wrote a simple "call back" Indexer class below ...

R = the returned type from the indexer P = the passed type into the indexer

All the indexer really does is pass the operations to the deployer and allow them to manage what actually occurs and gets returned.

public class GeneralIndexer<R,P>
    {
        // Delegates
        public delegate R gen_get(P parm);
        public delegate void gen_set(P parm, R value);
        public delegate P[] key_get();

        // Events
        public event gen_get GetEvent;
        public event gen_set SetEvent;
        public event key_get KeyRequest;

        public R this[P parm]
        {
            get { return GetEvent.Invoke(parm); }
            set { SetEvent.Invoke(parm, value); }
        }

        public P[] Keys
        {
            get
            {
                return KeyRequest.Invoke();
            }
        }

    }

To use it in a program or class:

private GeneralIndexer<TimeSpan, string> TimeIndex = new GeneralIndexer<TimeSpan,string>();

{
            TimeIndex.GetEvent += new GeneralIndexer<TimeSpan, string>.gen_get(TimeIndex_GetEvent);
            TimeIndex.SetEvent += new GeneralIndexer<TimeSpan, string>.gen_set(TimeIndex_SetEvent);
            TimeIndex.KeyRequest += new GeneralIndexer<TimeSpan, string>.key_get(TimeIndex_KeyRequest);

}

works like a champ especially if you want to monitor access to your list or do any special operations when something is accessed.

answered 2012-09-20T15:39:36.980

Your Answer