Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a new class in its own constructor

I have a User class. One of the properties needs to be an "associated" user, so it's type needs to be User. Right now when I initialize the class, I get a stack overflow when it tries to initialize the Associated property. Current code:

public class User {
    public User() {
        this.Associated = new User();
    }

    public User Associated { get; set; }
}

Is this doable or am I barking up the wrong tree?

like image 620
Michael Itzoe Avatar asked Sep 30 '11 15:09

Michael Itzoe


2 Answers

Does User.Associated have to be populated on construction? If you remove the assignment from the constructor you shouldn't get SO.

The reason you are getting an SO is because when you construct a User() it constructs a User() which in turn constructs a User() and it is turtles all the way down.

like image 152
Anthony Sottile Avatar answered Oct 26 '22 23:10

Anthony Sottile


You could use a lazy loaded method for your aggregated User class and not initialize it in the constructor:

public class User {
    private User _user;

    public User Associated 
    { 
        get
        {
            if (_user == null)
                _user = new User();
            return _user;
        }
    }
}
like image 44
CAbbott Avatar answered Oct 27 '22 00:10

CAbbott