0

Is it possible to write a C# function that takes in a bool and a float and resets that bool after a period of time (determined by the float)?

Specifically i'm asking for something like this:

void reset(bool a, float b){

    ... After a certain time period determined by b
    a = true;

}

So then to reset any bool i can just call reset, passing in a bool and a float which determines the time it takes until the bool is reset

This needs to work for any bool, not one specific bool. Thanks.

  • 1
    This seems to be an [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) Could you explain what is the problem that has lead you to think at this solution attempt? – Steve Oct 10 '19 at 10:33
  • 1
    It seems a classic XY problem. What the problem are you trying to solve? Can you accept a blocking solution? – Chayim Friedman Oct 10 '19 at 10:34

3 Answers3

1

There is not enough information to provide the full solution but here are some ideas:

  1. Pass the bool by reference. Please check Passing Value Types by Reference from Passing Value-Type Parameters (C# Programming Guide)
  2. Wait: a) with await Task.Delay b) with a timer c) start a new Task and don't wait for it here

Here's one way:

async Task ChangeMeAfter(ref bool makeTrue, float afterSeconds)
{
 await Task.Delay(TimeSpan.FromSeconds(afterSeconds);
 makeTrue = true;
}
tymtam
  • 31,798
  • 8
  • 86
  • 126
0

In order to check that bool value after the method is executed, you need to pass it as a reference (check here how can you do it: C# Pointers in a Method's arguments? ).

In the method body, you can use an timer to determine when to edit the bool's value (using the second parameter): https://learn.microsoft.com/en-us/dotnet/api/system.timers.timer?view=netframework-4.8

StefanaB
  • 184
  • 2
  • 11
-2
class Program
{
    static void Main(string[] args)
    {
        reset(false, 228.10803f);
    }

    public static void reset(bool a, float b)
    {
        float totalSeconds = b;
        Thread.Sleep(Convert.ToInt32(b));
        if(a)
        {
            a = false;
        }
        else
        {
            a = true;
        }
        Console.WriteLine("Value should be reset after certain time. Bool value is {0}",a);
        Console.ReadLine();
    }
}