C# DateTime (greetings)

If you are able to use C# 9+ as the language version, give the following a try.

C#:
string greeting = DateTime.Now.Hour switch
{
    >= 5 and < 12 => "Good Morning",
    >= 12 and < 17 => "Good Afternoon",
    >= 17 and < 21 => "Good Evening",
    _ => "Good Night"
};

Console.WriteLine(greeting);

I admit it is "cryptic" like the Kotlin example shared above, but I wanted to show it because it is one of the capabilities of the language.
 
  • Like
Reactions: Toz
val currentTime = LocalDateTime.now() val greetingMessage = when (currentTime.hour) { in 8..11 -> "Good Morning" in 12..15 -> "Good Afternoon" in 16..24 -> "Good Evening" else -> "Good Night" } println(greetingMessage)

In Kotlin you can use the "when" statement (aka "switch case") to compare numbers against ranges, like there currentTime.hour is compared against whether it is in 8..11 range.
You won't find this in Python, C/C++ or Java. Not sure about C#, its devs are constantly adding new features to the language to look more modern.
There is now switch case in Python. I think it was added in 3.10, iirc. Works like a charm.

You probably already noticed but, this code does not work as intended.

Only you'll have with this code is "Good Morning" from 5:00:00 To 11:59:59, and "Good Afternoon" for the rest.

You'll need to set boundaries explicitly for all.

e.g. for "Good Afternoon":
C#:
... currentTime.Hour >= 12 && currentTime.Hour < 17 ...
Yeah, that was pretty bad.

Also, Rust is fun.
 
Back
Top