Personalize message by the hour

Asked

Viewed 596 times

5

I wanted to personalize the greeting message depending on the time.

Ex:

Hora menor que 12h.
"Bom dia"

Hora menor que 18h.
"Boa tarde"

I did with if and else but wanted a better method.

//Pegando a hora
int hora = DateTime.Now.Hour;

#region saudação
//Personalizando a saudação
if (hora <= 11)
{
    Console.WriteLine("Bom dia " + nome + "!");
}
else if (hora <= 17)
{
    Console.WriteLine($"Boa tarde {nome}!");
}
else if (hora <= 23)
{
    Console.WriteLine($"Boa noite {nome}!");
}
else if (hora <= 5)
{
    Console.WriteLine($"Boa madrugada {nome}!");
}
#endregion
  • What’s wrong with using if-Else? , there’s nothing wrong or that needs to be improved in your code. Replacing with Switch case will not improve readability.

  • 2

    Your code contains a flaw, the way you implemented it, it will never display "Good Morning", which is between 00 and 5

1 answer

6


  • I hadn’t seen your answer before, although I like it, I have a slight impression that AP will use the idea without understanding how it works =D Of course this is not your problem (nor mine), it’s just a comment.

  • I get it. Created an array [0] Good morning [1] Good morning [2] Good afternoon [3] Good evening Divide the time by 6 and print the array that can be 0-3.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.