-1

i made a custom Dictionary

but when i try to set some value i got error

StackOverflowException: The requested operation caused a stack overflow.

i dont get error on getter only the setter

let me share my code

 public class myClass : Dictionary<object, object>
 {
    public myClass () { }
    public myClass (int x) { }

    public object this[object key] { get { return this[key]; } set { this[key] = value; } }

    public object Clone() {
      return  new Dictionary<object, object>(this);
    }
    public IEnumerator<DictionaryEntry> GetEnumerator() {
      return this.GetEnumerator();
    }
    
 }

data i tried to set to my class

        myClass   properties = new myClass ();
        properties ["235"] = "www";

i don't see any StackOverflowException in the setter how did this value make StackOverflow?

narcos
  • 11
  • 1
  • 3

1 Answers1

2

Here's the problem:

 public object this[object key] { get { return this[key]; } set { this[key] = value; } }

This cause an infinite recursion since the indexer is calling itself.
If you're going to inherit from a Dictionary<TKey, TValue>, you should change it to

 public object this[object key] { get { return base[key]; } set { base[key] = value; } }

Having said that, inheriting from a Dictionary is kinda like inheriting from List - which means it's probably a bad idea.

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121