Search code examples
c#visual-studio-express

Trying to set a name in a messagebox, depending on DateTime.now


To keep it short, i want to fill in name depending on the date. im not using any database, its pure c#.

below my current code.

DateTime dt = DateTime.Now;
string vandaag = dt.ToString("dd-MM-yyyy");
string bday = " has his/her birthday today";

Boolean name1 = DateTime.Now.Month == 3 && DateTime.Now.Day == 12;
Boolean name2 = DateTime.Now.Month == 6 && DateTime.Now.Day == 9;

if (name1) {MessageBox.Show(string.Format("Hello, today is {0}. name of person 1 {1}", today, bday), "Hello", MessageBoxButtons.OK);}

else if (name2) {MessageBox.Show(string.Format("Hello, today is {0}. name of person 2 {1}", today, bday), "Hello", MessageBoxButtons.OK);}

etc.

The code actually works, but like this im gonna repeat this code just for about anyone. Isnt there a way to have "name of person" filled in without having to repeat the same code over and over?


Solution

  • The first thing to do is to define a Person class like this one (expandable in future)

    public class Person
    {
        public string Name { get; set; }
        public DateTime dob {get;set;}
    }
    

    Then you need to build a list of your Person that you want to check for their birthday

    List<Person> people = new List<Person>()
    {
        new Person() {Name="Steve", dob = new DateTime(1960, 3, 26)},
        new Person() {Name="John", dob = new DateTime(1961, 7, 1)},
    };
    

    finally your code could search if today is the Date Of Birth for any of the people list with a simple linq code

    Person p = people.FirstOrDefault(x => x.dob.Month == DateTime.Today.Month && 
                                          x.dob.Day == DateTime.Today.Day);
    if (p != null)
        MessageBox.Show(string.Format("Hello, today is {0}. Birthday of person {1}", DateTime.Today, p.Name), "Hello", MessageBoxButtons.OK); 
    

    With this approach you need only to add other Person to the list using the format above and nothing else changes. However there is a problem because you could have more than one Person with the same Date Of Birth. In this case the code that search the list becomes

    List<Person> ppl = people.Where(x => x.dob.Month == DateTime.Today.Month && 
                                    x.dob.Day == DateTime.Today.Day).ToList();
    MessageBox.Show(string.Format("There are {0} people with this dob", ppl.Count));
    foreach(Person p in ppl)
        MessageBox.Show(string.Format("Hello, today is {0}. Birthday of person {1}", DateTime.Today, p.Name), "Hello", MessageBoxButtons.OK);