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?
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.
Your property is customizable.
prop2 = ... set setter, , , , , , , , , , , , , , , , , , , ...
prop2 = ...
, , .
, .
:
private string prop2; //Create a backing field public string Prop2 { get { return prop2; } set { prop2 = EditString(value); } }
prop2 get, ( ).
, (prop2) .
Error in the definition prop2. Both get and set methods simply pass into the property prop2and, therefore, induce infinite recursion.
prop2
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); } }
Have you looked at the call stack when an exception is thrown? You should see an endless list of setter calls for prop2.
You set the property for yourself
Source: https://habr.com/ru/post/1776745/More articles:Есть ли способ перечислить все вызовы и жестко заданные строковые параметры метода из сборки .Net? - reflectionReportViewer - ReportParameter - namespace WinForms vs WebForms - reportviewerHow to track where the appearance of the accessory on the right callout is when it was used - objective-cWhat exactly does the Response.Redirect ("~ / ...") response put in the HTTP response? - c #Check for flowLayoutPanel in C # - nullScan string containing spaces in C - cWebBrowser SetAttribute does not work (Password field) - c #Display and retrieve QMessageBox result from outside QObject - qtjquery parseFloat, parseInt - jqueryUnable to get basic Selenium + Capybara + Cucumber to work with Rails 3 - ruby-on-rails-3All Articles