I am learning C# and I have an exercise:
Design a class called Stopwatch. The job of this class is to simulate a stopwatch. It should provide two methods: Start and Stop. We call the start method first, and the stop method next. Then we ask the stopwatch about the duration between start and stop. Duration should be a value in TimeSpan. Display the duration on the console. We should also be able to use a stopwatch multiple times. So we may start and stop it and then start and stop it again. Make sure the duration value each time is calculated properly. We should not be able to start a stopwatch twice in a row (because that may overwrite the initial start time). So the class should throw an InvalidOperationException if its started twice.
My code works fine, but please review if I could do something better. Especially I do not like this part with the switch case block but I dont have any idea how I could improve it.
Stopwatch class:
using System;
namespace Stopwatch
{
public class Stopwatch
{
private DateTime _startDate;
private DateTime _endDate;
private bool _isRunning;
public void Start()
{
if (_isRunning)
throw new InvalidOperationException("Stopwatch is already running");
_startDate = DateTime.Now;
_isRunning = true;
}
public void Stop()
{
if (!_isRunning)
throw new InvalidOperationException("Stopwatch is not running");
_endDate = DateTime.Now;
_isRunning = false;
}
public TimeSpan GetDuration()
{
return _endDate - _startDate;
}
}
}
Program class:
using System;
namespace Stopwatch
{
class Program
{
static void Main(string[] args)
{
var stopWatch = new Stopwatch();
while (true)
{
Console.WriteLine("Enter 'start' to start Stopwatch\nEnter 'stop' to end Stopwach\nEnter any key to exit:\n");
var input = Console.ReadLine().ToLower();
if (input == "start" || input == "stop")
UseStopwatch(stopWatch, input);
else
return;
}
}
static void UseStopwatch(Stopwatch stopWatch, string command)
{
switch (command)
{
case "start":
try
{ stopWatch.Start(); }
catch (InvalidOperationException)
{ Console.WriteLine("stopWatch is already started\n"); }
break;
case "stop":
try
{
stopWatch.Stop();
Console.WriteLine("Duration: {0}\n", stopWatch.GetDuration());
}
catch (InvalidOperationException)
{ Console.WriteLine("stopWatch is not started\n"); }
break;
default:
break;
}
}
}
}
reset()
method in addition tostart()
andstop()
. \$\endgroup\$