Home > other >  Set variable inside void function
Set variable inside void function

Time:09-08

When I press the button, I want to assign the current time (start temp value) to the start time variable in the same class. How can i make it?

public class Simulator
{
TimeSpan start Time;
    private void b_start_Click(object sender, EventArgs e)
    {
       string tempDate = DateTime.Now.ToString("h:mm:ss");
       TimeSpan startTemp = TimeSpan.Parse(tempDate);
    }
}

CodePudding user response:

Instead of:

TimeSpan startTemp = TimeSpan.Parse(tempDate);

You can assign to the class member directly:

this.startTime = TimeSpan.Parse(tempDate);

Your member declaration seems to be incorrect...

TimeSpan startTime;

CodePudding user response:

You don't need to convert the current time to a string just to parse it one line later back to a TimeSpan. You can assign it directly from DateTime.TimeOfDay:

public class Simulator
{
    TimeSpan startTime;
    private void b_start_Click(object sender, EventArgs e)
    {
       startTime = DateTime.Now.TimeOfDay;
    }
}
  •  Tags:  
  • c#
  • Related