+ 1

StackOverflowException even without recursion [SOLVED]

When setting an object property I get a StackOverflowException for an unknown reason. The code involved does not include any recursion. To make the whole situation even more confusing, it happens before the code is called (see below). Relevant code: class Program { static void Main() { Person P1 = new Person(); P1.GivenName = "Alice"; //calls set for GivenName } } class Person { public string GivenName { get { return GivenName; } set { GivenName = value; } } }

1st Jan 2017, 12:42 PM
Maike
4 Respostas
+ 3
This is the first time on SoloLearn I've seen *anyone* mark their question [SOLVED]. There needs to be more of that somehow.
13th Jan 2017, 8:27 PM
Kirk Schafer
Kirk Schafer - avatar
+ 2
There is a recursion. You call GivenName setter from itself (GivenName = value, which is setter call). Use short syntax ("{ get; set; }") or create a local variable in class and use it in getter and setter.
31st Dec 2016, 11:18 PM
Ivan G
Ivan G - avatar
+ 1
Does the same problem occur if using the shortened version (public string GivenName { get; set; }) ?
31st Dec 2016, 9:34 PM
Dao
Dao - avatar
+ 1
does givenName variable is in lowcase? if yes, you are calling the get and set until the memory crash
31st Dec 2016, 10:52 PM
Nahuel
Nahuel - avatar