0

I can't find any .add() method and I don't know what I can do for this.

public class MyDictionary<TKey, Tvalue>
{ 
    private MyDictionary<TKey, Tvalue> md ;
    public MyDictionary (int size) 
    { 
       md = new MyDictionary<TKey, Tvalue>(size); 
    }
    public void AddItem(TKey key, Tvalue value)
    { 
      md[key] = value;
    }
}

There is red line under md.[key] and it says:

Cannot apply indexing with [] to an expression of type MyDictionary

Lucas Derraugh
  • 6,929
  • 3
  • 27
  • 43
katras
  • 29
  • 1
  • 1
    You need to write an [indexer](https://learn.microsoft.com/en-us/dotnet/csharp/indexers). But note that at the moment you'd have a stack overflow as soon as you call your constructor - because it will immediately recurse. – Jon Skeet Jul 05 '19 at 15:46
  • `md.Add(key, value); ` will solve your problem; to add new item to dictionary you need to pass respective key and value to add method. Method name is `.Add(key, Value);` not `.add(key, value)` – Prasad Telkikar Jul 05 '19 at 15:51
  • You realise that your `MyDictionary` doesn't inherit `Dictionary` so it won't have the methods that come with a `Dictionary`? So maybe your class declaration should look like this `public class MyDictionary : Dictionary` ? – Rand Random Jul 05 '19 at 15:55
  • Now its working and thanks – katras Jul 05 '19 at 17:27

1 Answers1

0
public void Add(TKey key, TValue value)
{
    this.Insert(key, value);
}

From this link

Sam Mullinix
  • 196
  • 1
  • 10