Simple Stop Watch implementation in C#

Below is a simple stop watch implemented in C#, enjoy!StopWatch

using System;
 
namespace StopWatchApp
{
    public class StopWatch
    {
        public DateTime StarTime { get; set; }
 
        public DateTime StopTime { get; set; }
 
        public string ClockState { get; set; }
 
        public void StartClock()
        {
            if(this.ClockState == "started")
                throw new InvalidOperationException("Invalid Operation");
            this.StarTime = DateTime.Now;
            this.ClockState = "started";
        }
 
        public void StopClock()
        {
            this.StopTime = DateTime.Now;
            this.ClockState = "stopped";
        }
 
        public TimeSpan ElapsedTime()
        {
            return this.StopTime - this.StarTime;
        }
    } 
}



Main Program

using System;
 
namespace StopWatchApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Enter Start to Start the Clock, 
             Enter Stop to Stop the Clock to see the elapsed time. 
             Enter Quit to exit.");
 
            var clock = new StopWatch();
            int alreadystarted = 0;
            while (true)
            {
                var inp = Console.ReadLine();                
 
                if (inp != "Quit")
                {
                    if (inp == "Start" && alreadystarted == 0)
                    {
                        clock.StartClock();
                        Console.WriteLine("\n\nClock started at -----{0}",
                            clock.StarTime);
                        alreadystarted = 1;
                        continue;
                    }
                    if (inp == "Stop" && alreadystarted == 1)
                    {
                        clock.StopClock();
                        Console.WriteLine("\n\nClock stopped at -----{0}",
                            clock.StopTime);
                        Console.WriteLine("\n\n+++++++Elapsed Time is >> {0}",
                            clock.ElapsedTime());
                        Console.WriteLine("\n\nPlay again! Enter Start 
                            to begin--\n\n");
                        alreadystarted = 0;
                        continue;
                    }
                    else
                    {
                        Console.WriteLine("Not a valid input!");
                        continue;
                    }
                }
                else
                {
                    break;
                }
                
            }
        }
    }
}

 

Add a Comment

Your email address will not be published. Required fields are marked *