A static property which returns true the first time, then always false after that

I'm looking to write C# simple statement using static bool which return true the first time, then always false.

    static bool _firstTime = true;
    static bool FirstTime
    {
            get
            {
                    bool old = _firstTime;
                    _firstTime = false;
                    return old;
            }
    }

This works, but i'm looking for something shorter without temporary variable (here "old").

Thanks.

3 answers

  • answered 2019-07-10 22:39 Rufus L

    You can return the result of an assignment in C#, which means you could do a comparison, and if firstTime is true, you can return the negative of assigning it to false:

    private static bool firstTime = true;
    public static bool FirstTime => firstTime ? !(firstTime = false) : firstTime;
    

    But your way is easier to understand.

    Note: this is exactly as thread safe as your original code (which you said "works"), meaning it's not thread safe.

  • answered 2019-07-10 23:21 Renat

    You may abuse that && is a short circuit like below. But don't use it at work, as your first example is much more easier to read. And it isn't thread safe.

    static bool _firstTime = true;
    
    private static bool FirstTime
        => _firstTime && !(_firstTime = false);
    

  • answered 2019-07-11 00:20 NPras

    If you want something thread-safe and compact, Interlocked.Exchange() fits the bill. It will set your variable and return the old value (exactly what you did in your code) in a thread-safe manner.

    The only caveat is that your private field can't be a bool. But whatever happens behind a public property shouldn't matter externally anyway.

    static int _isFirstTime = 1;
    public static bool IsFirstTime => Interlocked.Exchange(ref _isFirstTime, 0) != 0;