Thread: Can i have a generic indexer this[TKey key] property? it requiers only int why?

  1. #1
    Registered User
    Join Date
    Nov 2017
    Posts
    4

    Can i have a generic indexer this[TKey key] property? it requiers only int why?

    Code:
     public class MyDictionary<TKey, TValue> : MyIDictionary<TKey, TValue>
        {
            private object[] _items;
            //private int index = 0;
            public MyDictionary()
            {
                _items = new object[10];
            }
    
    
            public TValue this[TKey key]
            {
                get
                {
                    return (TValue)_items[key];//cannot implicitly convert type 'TKey' to 'int'
                }
                set
                {
                    _items[key] = value;
                }
            }

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    You can do it, but where you went wrong is that an array of objects expects the index to be an int. You have to search the array _items yourself and return the right object.

    Maybe something like this is a good start.
    Code:
    public class MyDictionary<TKey, TValue> : MyIDictionary<TKey, TValue>
    {
       private KeyValuePair<TKey, TValue>[] _items;
       private int index = 0;
       public MyDictionary()
       {
           _items = new KeyValuePair<TKey, TValue>[10];
       }
    
    
       public TValue this[TKey key]
       {
           get
           {
               foreach (KeyValuePair<TKey, TValue> kvp in _items)
               {
                      if (key.Equals(kvp.Key))
                         return kvp.Value;
               }
               throw new System.ArgumentOutOfRangeException(key.ToString(), "not in dictionary");
           }
           set
           {
               _items[index] = new KeyValuePair<TKey, TValue>(key, value);
               ++index;
           }
       }
    }
    Nothing was tested.
    Last edited by whiteflags; 12-24-2017 at 03:04 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Indexer question...
    By stumon in forum C# Programming
    Replies: 8
    Last Post: 03-16-2010, 07:08 AM

Tags for this Thread