user1845777 user1845777 -4 years ago 99
C# Question

C# Class and return value

My assignment specifies that I must create 6 classes, now in one of these classes calls (player) which contains the usual, like name, gender etc. !BUT! there has to be a method that returns the age of the player in years. Now I've written the following code, but I feel like it's maybe needlessly long, so I am looking for any helpful advice.

class Player
{
private string firstName;
private string lastName;
private List<string> middleNames;
private DateTime birthday;
private string nationality;
private string gender;

public Player(string firstName, string lastName, List<string> middleNames, DateTime birthday, string nationality, string gender)
{
this.firstName = firstName;
this.lastName = lastName;
this.middleNames = middleNames;
this.birthday = birthday;
this.nationality = nationality;
this.gender = gender;
}

public string FirstName
{
get
{
return firstName;
}
set
{
firstName = value;
}
}

public string LastName
{
get
{
return lastName;
}
set
{
lastName = value;
}
}

public List<string> MiddleNames
{
get
{
return middleNames;
}
set
{
middleNames = value;
}
}

public DateTime BirthDay
{
get
{
return birthday;
}
set
{
birthday = value;
}
}

public string Nationality
{
get
{
return nationality;
}
set
{
nationality = value;
}
}

public string Gender
{
get
{
return gender;
}
set
{
gender = value;
}
}

public int GetAge(DateTime currentDate)
{
int age = currentDate.Year - birthday.Year;
if (currentDate.Month - birthday.Month < 0 || (currentDate.Month - birthday.Month == 0 && currentDate.Day - birthday.Day < 0))
{
--age;
}

return age;
}
}

Answer Source

Your code for calculating age seems reasonable. This is a little shorter, if that's what you're looking for. This does not work if they were born in a leap years, or if it's currently a leap year.

public static int Age()
{
    return (DateTime.Today.DayOfYear > birthday.DayOfYear)
        ? DateTime.Today.Year - birthday.Year - 1
        : DateTime.Today.Year - birthday.Year;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download