Mostafa Ghorbani
Mostafa Ghorbani

Reputation: 445

How to get a time span between two methods in c#?

I am trying to make a stopwatch with C# as an exercise for myself. my plan was to make two methods " start()" and " stop()" then call these from my stopwatch class in my main. the problem I have is that I do not know how to get the time span between these two.

for your information, this is how I want the program to work: if they typed s the timer starts and when press enter or type f the time will be shown to them.

this is the code I have written so far, but got stuck when getting the time span.

 class StopWatch
{
    DateTime starting = DateTime.Now;
    DateTime finishing = DateTime.Now;
    
    
    public void start()
    {
        Console.WriteLine(starting);
    }

    public void stop()
    {
      
        Console.WriteLine(finishing);
    }

    
}
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("type s to start and f to stop");
        var input = Console.ReadLine();
        var stopwatch = new StopWatch();
        if (input.ToLower() == "s") { stopwatch.start(); }
        var Input2 = Console.ReadLine();
        if (Input2.ToLower() == "f") { stopwatch.stop(); }

        

        Console.ReadKey();
    }
}

Upvotes: 0

Views: 426

Answers (1)

AlWo23
AlWo23

Reputation: 72

I agree with the comment to use what already exists in the library, but since you said you are doing this as an exercise, here is some feedback:

To answer you direct question how to get a TimeSpan: var duration = finishing - starting;

The current implementation will not do what you intend to do, since you set both starting and finishing at object creation time: field initializers are executed before any constructor code. So you should set starting in the start() method and finishing in the stop() method. Then you can calculate the duration as shown above in the stop() method, too.

And allow me a little side note on naming: "starting" and "finishing" are progressive forms in English, but here you want to name specific values. Therefore I'd recommend "startTime" and "endTime"/"stopTime".

Upvotes: 6

Related Questions