0

My C# code is :

private int ageInDays()
{
    string[] month = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
    int age = 0;

    DateTime birthDay = new DateTime(Convert.ToInt32(yearCombo.Text), Array.IndexOf(month, monthCombo.Text) + 1, Convert.ToInt32(dayCombo.Text));
    MessageBox.Show(birthDay.Date.ToString());
    DateTime tempDay = birthDay;
    DateTime today = DateTime.Today;
    while (tempDay != today)
    {
        age++;
        tempDay.AddDays(1);
    }
    return age;   
}

When I execute it, the program shows no progress at all. It probably hangs or falls into an infinite loop. Is it due to the heavy amount of processing the program has to do? Why am I not getting any output?

If the above method of calculating the age solely in days is flawed, what's a better/simpler way?

Somenath Sinha
  • 1,174
  • 3
  • 16
  • 35

1 Answers1

3

DateTime is an immutable struct. You have to assign what DateTime.AddDays returns to the variable:

tempDay = tempDay.AddDays(1);

You can get the result in an easier and more efficient way with TimeSpan.Days:

int age = (DateTime.Today - birthDay).Days;
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939