Object Oriented Programming: Timer | Code Example C#

Today we will try to understand and practice the basics of object oriented programming by doing a fun project.

Design a class called timer. This class will simulate a timer. 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 timer 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 timer twice in a row (because that may overwrite the initial start time). So the class should throw an InvalidOperationException if its started twice.

Before start coding lets look below at the logic Flow Chart.

Timer Stopwatch

Code Example :

You can create a Console App Project in Visual Studio and lets start coding,

using System;
using System.Diagnostics;

public class Program
{
    public static void Main()
    {
        // create a new instance of the class Timer
        // creating an object 
        Timer myTimer = new Timer();
        bool continueAsking = true;
        myTimer.DoNothing();

        do
        {
            Console.WriteLine("What do you want to do?"); // "0" to start, "1" to stop, "x" to exit

            var input = Console.ReadLine();

            if (input == "0")
            {
                //try catch
                try
                {
                    myTimer.Start();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            if (input == "1")
            {
                myTimer.Stop();
                Console.WriteLine($"The time was {myTimer.StopWatch.Elapsed}");
            }

            if (input == "x")
            {
                continueAsking = false;
            }
        } while (continueAsking);
    }
}

public class Timer : Clock
{
    // define properties
    public bool IsTimerWorking { get; set; }
    public Stopwatch StopWatch { get; set; }

    // variable
    string something = "something";

    // define methos - this is what the class do

    public void Start()
    {
        if (IsTimerWorking) // already counting time
        {
            //we have to prevent from starting again
            throw new InvalidOperationException("Nope, you can't do that");
        }
        else
        {
            // kick off the timer
            StopWatch = Stopwatch.StartNew();

            IsTimerWorking = true;
        }
    }

    public void Stop()
    {
        // actuall stop the watch
        StopWatch.Stop();

        // toggle the flag back to false
        IsTimerWorking = false;
    }
}

public class Clock
{
    public void DoNothing()
    {

    }
}
Advertisements

Leave a Reply