Design a Stopwatch in C#

NANDA KISHORE
5 min readJun 8, 2020

Welcome to another blog. This time I am here with a C# tutorial.In this tutorial I am going to present you with the solution of first exercise problem in C# intermediate level course by Mosh (Moshfegh) Hamedani in Udemy. For those of you who are unware of this course I have given the question below.

For those, who can’t wait for the code I have given link to files here.

Based on the exercise, we are supposed to write a program which allows users to start and stop the stopwatch and print the time span to the console. So, let’s think about a way of organizing the code based on the responsibilities. The features such as starting the stopwatch, stopping the stopwatch and noting the time span should be placed in one class say Stopwatch. The main class will be given the responsibilities of taking the customer input and printing out the time span.

Before starting the coding, below is the losely written algorithm for this task.

i) Read the input from the user.
ii) If the input is start -> start the stopwatch
If the input is stop -> throw an InvalidOperation exception
iii) Read another input from the user
iv) If the input is stop -> stop the stopwatch and print the time span
If the input is start -> throw an InvalidOperation exception
v) Repeat from step (i).

Now first let us build the main class.

Main Class:

The process starts with prompting user to enter S to start the stopwatch and Q to quit as shown in the code block below. The condition in the while is used to check if the input is null or empty. If the input is null or empty then,
will become true but since we used! before the expression it will evluate to false if the input is null, otherwise it will be true.Whenever, the user input is null we consider it as exit clause and the program stops executing as there is no code after the while block.

In the while block we check whether the user entered S (to start) or Q (to stop). Since, we want the program to execute irrespective of the case of the user input I am comparing the input with both small s and captial S. There are multiple ways of acheiving this. You can just convert the user input into lower case or upper case before checking. This way you can get the things done by just one boolean expression. But, I just went in my way to show two possible ways.

The third argument in the string.Equal( ) method in else block tells how to comapre the Strings. There are total 5 options that you can pass to this method as third argument. The option that I used here tells the C# runtime to ignore case. (If you want to know more about “StringComparison.CurrentCultureIgnoreCase” goto official documentation on MSDN.) So, if the input is “S” or “s” we call Start( ) method on Timer which starts the stopwatch and prints a note on the console asking user to press Q to quit. Stopping the stopwatch works in similar manner but it has one extra message which prints the time span.

After performing start and stop operations once, the user should be able to start and stop the stopwatch again any number of times without restarting the program. For this reason, we read input from the user before exiting the while block and repeat the above process.

Stopwatch Class:

Let’s talk about the stopwatch class where all the code related to the core funcitons (basically start and stop) of the stopwatch are placed.It has two methods Start( ) and Stop( ) and four fields as given below.

Since, it is a boolean property it can exist in two states or we consider as stopwatch in running state, as stopwatch in stopped state.

Whenever the start method is called, we should first check whether the stopwatch is already started. This can be acheived by checking _isStart flag. If the _isStart flag is then we throw an InvalidOperationException as it means that stopwatch is already running and you can not perform multiple starts or stops consecutively. If the _startTime is false then we proceed further to record current time and set the _isStart flag to true indicating that stopwatch is now started.

Next the last thing to do is implement the Stop( ) method. Here also, we check the stopwatch running status using _isStart. We should try to stop the
stopwatch only if it is already up and running. If _isStart is false we should throw the InvalidOperationException and exit. If _isStart is true we should record the stop time usind DateTime.now and check the time span by subtracting _startTime from _stopTime. Then, set the _isStart flag to flase and return the _timeSpan to the main class.

So, we are done with the implementation of the stopwatch. If you have followed the exact implementation you should be noticing that your application crashes when you perform ivalid operations that is because I did not handle the exception. If you feel like handling the exception just put the Start( ) and Stop( ) methods in try catch block and your application will not crash anymore.

Originally published at http://sayitkishore.wordpress.com on June 8, 2020.

--

--

NANDA KISHORE
0 Followers

web developer based in Hyderabad,India.