Monday, 8 August 2016

c# - Boolean Statement True For Length of Time



I have the following code:



private Boolean _penny = false;

public void InputTextbox_KeyDown(object sender, KeyEventArgs e)

{
if (!_penny)
{
if (e.KeyCode == Keys.Enter & InputTextbox.Text.Contains("penny"))
{
_penny = true;
OutputTextbox.Text = "yes sir";
InputTextbox.Text = "";
}
}

}


This clears the InputTextbox so that it is ready for further input, and the commands that follow only run if the Boolean for _penny = true (ie: that the program has been ordered to listen for further commands).



At the moment, each text command ends with "_penny == false" so that the program essentially stops listening for anything.



My question is, can this Boolean value stay "true" for a length of time? ie: User says "penny", and they can ask multiple input questions for a number of minutes without having to say "penny" again.


Answer



While you could use a timer, that seems like overkill to me. All you need to do is track an expiry date/time:




private bool CurrentlyValidated
{
get
{
return DateTime.Now < _expiryTime && _validated ;
}
set
{
_validated = value ;

_expiryTime = DateTime.Now.AddMinutes(5) ;
}
}
private bool _validated ;
private DateTime _expiryTime ;

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...