Stackoverflow Exception caused by property
I have a User class that has a property called Creator which is of type User (the user who created this user)
public class User {
public User()
{
UserName = "";
EmailAddress = "";
}
public S开发者_运维百科tring UserName { get; set; }
public String EmailAddress { get; set; }
//bunch of other properties
public User Creator { get; set; }
}
I am getting a Stackoverflow exception on the line UserName = "";. I am assuming it is because of the Creator property getting stuck in a big loop. Why does this happen if I haven't set Creator to a new User? Is there a way I can stop this from happening?
I will bet money your UserName
Setter looks like this
public string UserName
{
get { return UserName; }
set { UserName = value; }
}
This is causing the infinate recursion. You need to either design it like the Creator
property you had, or do this
private string _UserName;
public string UserName
{
get { return _UserName; }
set { _UserName = value; }
}
EDIT:
I doubt the Creator
property has anything to do with the issue because that value will just be null in the constructor
My guess is you are initializing Creator somehow which is causing an infinite number of User's to be created leading to a StackoverflowException.
Here's an example which produces just that:
public List<User> CreatUsers()
{
List<User> users = new List<User>;
//Some DB call to get a list of users
foreach (var record in userlist)
List.Add(CreatUser(record));
}
public User CreateUser(?? record)
{
User user = new User();
//Set properties
if (record has creator) //pseudo-code
user.Creator = CreatUser(record.Creator); //guessing as to record.Creator
}
public class User
{
public User()
{
UserName = ""; //Stackoverflow on this line.
EmailAddress = "";
}
public String UserName { get; set; }
public String EmailAddress { get; set; }
public User Creator { get; set; }
}
//{Cannot evaluate expression because the current thread is in a stack overflow state.}
Actually, I have no idea how to fix it because it's too hard to guess at all his code, lol.
I have a user where the creator is itself. I guess it was a data problem not a code problem. Thanks for looking at this anyways.
精彩评论