Click here to Skip to main content
15,896,497 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I was trying to figure out how could I do something if age is between, for example 16-21.

What I have tried:

I have a class called Person.
C#
    public string Name { get; set; }
    public string Surname { get; set; }
    public DateTime Age { get; set; }
}


I was trying to figure out to determine the age between certain values. So let's say that:
Person:
Name: Blah
Surname: Nah
Age: 20

I was trying to create an if statement saying
if age is between 16 and 21 do something etc.

How could I do that?

Thanks in advance.
Posted
Updated 26-Nov-17 2:59am

 
Share this answer
 
Comments
phil.o 27-Nov-17 6:03am    
I had forgotten your article, and the odds of computing an age value. Have my 5.
Actually, you should not have an Age DateTime property. It should be named DateOfBirth (for example). The Age property can then be computed when you need it, from the date of birth.
This way:
C#
public DateTime DateOfBirth { get; set; }

public int Age
{
   get { return (DateTime.Today - DateOfBirth).Days / 365; }
}

Analyze:
- (DateTime.Today - DateOfBirth) returns a TimeSpan value.
- The total number of days in the TimeSpan is divided by the average number of days in a year to give an approximation of the age.

Note that the Age property is read-only, as it is computed everytime the property getter is called. It thus always returns the current age.

Hope this helps. Kindly.
 
Share this answer
 
v4
Comments
fellanmorgh 26-Nov-17 8:25am    
Hey, thats great. Was able to work out the age of a person. Thanks for the help :)
BillWoodruff 27-Nov-17 4:41am    
why not (DateTime.Today - DateOfBirth).Years ?
phil.o 27-Nov-17 5:39am    
Because last time I checked, TimeSpan structure does not have a Years property :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900