1

What is wrong with this code? I keep getting a StackOverlflowException..

public class Places
{
    public string Title { get; set; }
    public string Content { get; set; }
    public double Latitude { get; set; }
    public double Longtitude { get; set; }    


    public List<Places> allPlaces = new List<Places>
    {
        new Places { Title = "test", Content = "test\ntest", Latitude = 52.23057, Longtitude = 5.84582 },
        new Places { Title = "testt", Content = "dfsdf", Longtitude = 52.35589, Latitude = 4.92119 }
    };
}
Allon Guralnek
  • 15,813
  • 6
  • 60
  • 93
user3478148
  • 433
  • 1
  • 8
  • 26

1 Answers1

5

Since allPlaces is an instance field, it is initialized during construction of a Places object. So you create a Places object, which creates a List<Places>, which creates another Places object in its collection initializer, which creates another List<Places> of its own... a never ending recursion.

You probably wanted to create a static allPlaces field, which would create only one list. Add the static keyword to the field as follows:

public static List<Places> allPlaces = ...
Allon Guralnek
  • 15,813
  • 6
  • 60
  • 93
  • That's not an option, because I want to use the list in another class. – user3478148 Apr 19 '14 at 18:13
  • @user3478148: Please provide a detailed explanation of what you're trying to accomplish. It is difficult to help you if you provide so little information. Otherwise we're left to making guesses, like I did here. – Allon Guralnek Apr 19 '14 at 18:16
  • I get it, I'm sorry. I'm trying to set a list in a class called Places.cs. Then I'm trying to receive the info inside the list of this class in another class, using this code: `Places places = new Places(); foreach (var place in places.allPlaces) { string test = place.Content; }` – user3478148 Apr 19 '14 at 18:19
  • @user3478148: With the static field that I suggested in my answer, you can do the following anywhere in the code (from any class): `foreach (var place in Places.allPlaces)`. Notice the capital P in `Places` which denotes the class name, rather than an instance of the class. Using the type name allows accessing static members. Read more about it [here](http://msdn.microsoft.com/en-us/library/79b3xss3.aspx) under the *Static Members* section. – Allon Guralnek Apr 19 '14 at 18:25