C# - Stopwatch (timer) loop

Alexandru Teodor 91 Reputation points
2022-07-06T08:01:05.73+00:00

In a VS 2019 WindowsFormsApp, using C#, I am trying to conditionlly set/start a Stopwatch timer in a loop.

Stopwatch[] timer_ = new Stopwatch[] { null, null, null, null, null, null, null };  
for (int i = 1; i <= 6; i++){  
	if (enable_timer_[i].Checked == true) {  
		 timer_[i].Start();  // <== System.NullReferenceException: 'Object reference not set to an instance of an object.'  
	}  
}  

I also tried setting the "timer_" as a null List, with no success (Cannot implicitly convert type 'System.Collections.Generic.List<System.Diagnostics.Stopwatch>' to 'System.Diagnostics.Stopwatch').
I just cant figure out how to correctly initialize and start dynamic timers variable names...

Help would be apreciated :)

Thanks

Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2022-07-06T08:08:21.707+00:00

    Try this:

    Stopwatch[] timer_ = new Stopwatch[] { null, new Stopwatch(), new Stopwatch(), new Stopwatch(), new Stopwatch(), new Stopwatch(), new Stopwatch() };  
    

    or this:

    for (int i = 1; i <= 6; i++)  
    {  
       if (enable_timer_[i].Checked)   
       {  
          if( timer_[i] == null) timer_[i] = new Stopwatch( );  
          timer_[i].Start();   
       }  
    }  
    

    By the way, maybe you should have a loop between i=0 and i < 6?

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.