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?
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.
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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With