I’m pretty new to C# and got this assignment. I have a class called person with some details, of which one is the social security number (CPR number). From this number I need to calculate the age of this person. It needs to fit in this, according to assignment, if i understand it right:
public class Person
{
int _Cpr;
public int Age
{
get
{
return (age calculation from cpr number somehow)
}
}
}
I however have no idea how to do so – I’m guessing I need to compare the social security number integer having this form: DDMMYYXXXX to the current date, and return the difference in rounded down years – but I have no idea how to do so.
I’m starting to get the picture as how to calculate the age – What I’m still lost on, is how to fit this into the code i have. The description I have says that the Age should be a “calculated property” – But I can’t create variables to use inside a class definition as far as i know, so i can’t really do all the steps required to make Cpr into Age – Can I?
I assume this is homework so let me try to push you in the right direction instead of simply providing the answer.
You have to extract the birth date from the social security number. By doing integer divisions by powers of 10 you can “chop” of digits from the right. By doing modulo operations by powers of 10 you can keep the number of digits you need:
In C# you can use the
DateTimeclass to represent a point in time (e.g. the birth date). The fieldDateTime.Nowcontains the current time.You want to get the age in years (rounded down) so you will have substract the
Yearproperty of the twoDateTimevalues. You also have to take into account if the person already had his birthday this year.Spoiler ahead
The largest CPR is 3112999999 and that number is actually larger than
Int32.MaxValue. This means that you have to change the type of_Cprtouint(orlong). The code below also takes into account the rule described by TheKaneda to get the four digit year from the two digit year.Even though the code is surprisingly complex it doesn’t handle the situation when a person is born on February 29. To improve the code it should be refactored into separate parts that deals with extracting the birth date and calculating the age. The last part should deal with the Feburary 29 issue and depending on culture you may discover that in non-leap year people born on February 29 celebrate their birthday February 28.