I get a StackOverflowException error in my nested class when given a C # property function

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 I'm having a problem with. When I try to initialize an object that is of type Class1, it throws a StackOverflowException. what am I doing wrong?

+3
source share
7 answers

Prop2 sets / returns Prop2 ... which calls Prop2 to get / set the value of Prop2, which calls Prop2 ... see where it goes?

This happens until the computer / runtime runs out of storage space for the call stack and dies.

+4
source

Your property is customizable.

prop2 = ... set setter, , , , , , , , , , , , , , , , , , , ...

, , .

, .

:

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

prop2 get, ( ).

+3

, (prop2) .

+1

Error in the definition prop2. Both get and set methods simply pass into the property prop2and, therefore, induce infinite recursion.

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

You need to add a support field here to save the property value like this:

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

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

0
source

You set the property for yourself

0
source

Source: https://habr.com/ru/post/1776745/


All Articles