-1

I'm attending an exam at Tuesday in FOOP (described in title), and I've handed in a programme. Problem is that I don't quite understand the following bit. It's a method for calculating a persons age:

public static int CalculateAge(DateTime dob)
{
    int years = DateTime.Now.Year - dob.Year;

    if ((dob.Month > DateTime.Now.Month) || (dob.Month == DateTime.Now.Month && dob.Day > DateTime.Now.Day))
        years--;

    return years;
}

I couldn't figure it out myself, so I looked it up on the internet. I don't know what happens inside the if statement. It should be mentioned that I've a Datetime variable called dob

Luiso
  • 4,173
  • 2
  • 37
  • 60

1 Answers1

1

What this code is doing, is determining a person's age based on their date-of-birth relative to the current date.

Let's take a look at the first line of code:

int years = DateTime.Now.Year - dob.Year;

What they are doing on the line above is determining overall how many years that the person has been alive.

Now, let's take a look at the conditions inside of the if statement. First, we will take a look at the left-hand-side of the || (means or-else, but will be treated as or for this code-snippet) operator.

(dob.Month > DateTime.Now.Month)

What this statement does is evaluate whether or not the current month is ahead of the person's birth-month. Then, consider the right-hand-side of the || operator.

(dob.Month == DateTime.Now.Month && dob.Day > DateTime.Now.Day)

The above conditional asks the question of whether or not this is their birth-month, and if so, is their birthday in the future? If the answer to either or these conditionals is yes, then the person has not reached their birthday. So, we subtract off one year from the total number of years as follows:

years--;

To help you think about this better, one could ask "just because this is the 16th year you've lived during, does that mean you are actually 16 complete years old?"

Snoop
  • 1,046
  • 1
  • 13
  • 33
  • I really think you should have left the OP to think about this for as long as it took. – Ian Jun 18 '16 at 21:51