user2064345
user2064345

Reputation: 1

RE return time span as a double in if statement

Re my question about time span before. What I am trying to do. I am trying to auto update my text box then time elapses. And with code below it works just fine:

public  void AutoSaveTimer()
{
   timer = new System.Timers.Timer ();
   timer.AutoReset= false ;
   timer.Elapsed += new System.Timers.ElapsedEventHandler (timer_Elapsed);
   timer .Interval = GetInterval();
   timer.Start ();
}

public  double GetInterval()
{      
   DateTime now = DateTime .Now;
   return ((60-now.Second )*1000-now.Millisecond );
}

public void timer_Elapsed ( object sender ,System .Timers .ElapsedEventArgs e)
{
   UpdateLogDatabase();

   timer .Interval =GetInterval ();
   timer .Start ();
}

private void AutoSaveTimerStop()
{
   timer = new System.Timers.Timer();
   timer.Stop();
}

But if I try to check user options in if statement the method is not returning double I am getting error: Use of unassigned variable.

  public double GetInterval()
  {
      double d;
      DateTime now = new DateTime();

      if (cb5Min.Checked== true)
      {
          d= ((60 - now.Second) * 1000 - now.Millisecond);
      }
      else if (cb15Min.Checked)
      {
          d= ((900 - now.Second) * 1000 - now.Millisecond);
      }
      return d;
  }

Thanks for your replies.

Upvotes: 0

Views: 281

Answers (2)

CodeCaster
CodeCaster

Reputation: 151586

I am getting error: Use of unassigned variable.

Try to learn to understand compiler errors. If both checkboxes are not checked, you return an unassigned d. You'd better initialize d where you declare it, for example to 0.

Upvotes: 1

Habib
Habib

Reputation: 223237

I am getting error: Use of unassigned variable.

You are trying to return your variable d from your method, you have declare it but haven't initialized it, initialization is done in the if block and compiler can't determine if that part of code would be reached. So its better if you can assign some default value to d like:

double d = 0;

or in your code you can use another else block to ensure that d is initialized to some value before being returned.

Upvotes: 1

Related Questions