create a timer that counts down in csharp

Here is an example of how to create a countdown timer in C# using the Timer class:

main.cs
using System;
using System.Timers;

class CountdownTimer
{
    static Timer timer = new Timer();

    static void Main()
    {
        int countdownSeconds = 60;

        timer.Interval = 1000; // 1 second
        timer.Elapsed += OnElapsed;
        timer.Start();

        Console.WriteLine($"Countdown started for {countdownSeconds} seconds...");
        Console.ReadLine();
    }

    static void OnElapsed(object sender, ElapsedEventArgs e)
    {
        int countdownSeconds = 60;
        countdownSeconds--;
        
        Console.WriteLine($"Countdown: {countdownSeconds} seconds left...");

        if (countdownSeconds == 0)
        {
            timer.Stop();
            Console.WriteLine("Countdown complete!");
        }
    }
}
744 chars
34 lines

In this example, the timer variable is an instance of the System.Timers.Timer class. It is used to trigger the OnElapsed event every second (defined by the Interval property).

The OnElapsed method is the event handler for the timer's Elapsed event. It simply decrements a countdownSeconds variable by one, and outputs the current value to the console. When the countdownSeconds reaches zero, the timer is stopped and a message is printed to the console.

gistlibby LogSnag