The name and the age of a person should be read-only. Name changes should be covered by methods like ChangeName(). The age is a calculated value depending on the birthdate.
Also make the GetOldest() method a little bit more robust:
namespace CsharpExamples
{
using System;
using System.Collections.Generic;
using System.Linq;
class Person
{
public int Age
{
get
{
return DateTime.Now.Subtract(this.Birthdate).Days / 365;
}
}
public DateTime Birthdate { get; private set; }
public string Name { get; private set; }
public Person(string name, DateTime birthdate)
{
this.Birthdate = birthdate;
this.Name = name;
}
public override string ToString()
{
return string.Format("{0}:{1}", this.Name, this.Age);
}
}
class PersonPopulation
{
private readonly List<Person> persons = new List<Person>();
public int Count
{
get
{
return this.persons.Count;
}
}
public Person GetOldest()
{
return this.persons.OrderByDescending(x => x.Age).FirstOrDefault();
}
public void Add(params Person[] persons)
{
this.persons.AddRange(persons);
}
}
class Test
{
public static void Main()
{
var population = new PersonPopulation();
var person1 = new Person("Ayoub", new DateTime(1990, 1, 1));
var person2 = new Person("Saeed", new DateTime(1995, 1, 1));
var person3 = new Person("Mahdi", new DateTime(2000, 1, 1));
Console.WriteLine("Oldest Person is --> " + population.GetOldest());
population.Add(person1, person2, person3);
Console.WriteLine("Oldest Person is --> " + population.GetOldest());
Console.WriteLine("population: " + population.Count);
Console.ReadLine();
}
}
}
You can implement the GetOldest() method either as method as you did or as property. I don't favorite any. But when you name methods: Get and Set are reserved verbs for explicit getter and setter methods. So FindOldestPerson() is a slightly better name.
No comments:
Post a Comment