I am developing a database application in C# using VS. I have a class called Crew and has its own fields such name, date of birth ... etc. I want the user to specify some of the fields, while others to be automatically calculated/ figured out by the application itself. Such as age to be calculated from the date of birth. Here is how I am doing this:
[Required]
[DisplayName("Date of Birth")]
public DateTime DOB
{
set { }
get { return DOB.Date; }
}
public int Age
{
get { return Convert.ToInt32(DateTime.Now.Year) - Convert.ToInt32(DOB.Year); }
}
While debugging, I fill out the fields for a person and hit the create button to save to the database, but an exception arises saying the following:
System.StackOverflowException occurred HResult=0x800703E9 Message=Exception of type 'System.StackOverflowException' was thrown.
In the getter for DOB, you reference DOB. So then it has to access the getter for DOB, which references DOB. So it has to access DOB....
A property cannot access itself when trying to get it's value, or you'll enter an infinite loop and get a SO exception. You can get around this by having a private backing field that stores the value, then access that in the property getter:
private DateTime _dob;
public DateTime DOB
{
get { return _dob; }
set { _dob= value; }
}
User contributions licensed under CC BY-SA 3.0