Question

public class Class1
    {
        public Class1()
        {
            prop = new Class2();
        }
        public Class2 prop { get; set; }

        public class Class2
        {
            public Class2()
            {
                this.prop2 = "nikola";
            }

            public string prop2 { get { return prop2; } set { prop2 = EditString(value); } }

            public string EditString(string str)
            {
                str += " plavsic";
                return str;
            }
        }
    }

this is my code that i have problem with. When i try to initialise object that is type of Class1 it throws an StackOverflowException error. what am i doing wrong?

Was it helpful?

Solution

Prop2 sets/returns Prop2... which calls Prop2 to get/set the value of Prop2, which calls Prop2... see where this is headed?

That keeps happening until the computer/runtime runs out of space to store the call stack, and dies.

OTHER TIPS

Your property is setting itself.

The line prop2 = ... in the property setter calls the property setter, which calls itself again, which calls itself again, which calls itself again, which calls itself again, which calls itself again, which calls itself again, which calls itself again, which calls itself again, which calls itself again, which calls itself again, which calls itself again, which calls itself again, which calls itself again, which calls itself again, which calls itself again, which calls itself again, which calls itself again, which calls itself again, which calls itself again ...

The getter does the same thing, except that you never call it.

You need to make a backing field for the property to get and set.

For example:

private string prop2; //Create a backing field
public string Prop2 {
    get { return prop2; }
    set { prop2 = EditString(value); }
}

You are returning prop2 in the get, that causes the stack overflow (infinite recursion is bad).

You are in an infinite loop because you are setting the property (prop2) to itself.

The error is in the definition of prop2. Both the get and set methods simply call back into the prop2 property and hence induce infinite recursion.

public string prop2 { 
  get { return prop2; // <-- This just calls prop2 get again}
}

You need to add a backing field here to store the value of the property like so

private string m_prop2;
public string prop2 { 
  get { return m_prop2; } 
  set { m_prop2 = EditString(value); } } 

Have you looked in the call stack when the exception is thrown? You should see an endless list of calls to the setter for prop2.

You are setting to the property to itself

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top