Search code examples
c#staticpersist

C# static variables not persisting?


Below is my code snippet, the variable "_lastError" doesn't seem to persist after it is set then accessed elsewhere.

Can anyone give a heads up on what I missed or done incorrectly? I've debugged the program, setting a breakpoint at both the getter and the private setter. Nothing else seems to be accessing nor modifying the value of "_lastError" other than where it was intended to.

class Utils
{
    private static string _lastError;
    public static string LastError
    {
        get
        {
            string lastError = Utils._lastError;
            Utils._lastError = string.Empty;
            return lastError;
        }

        private set
        {
            Utils._lastError = value;
        }
    }

    public static void Foo()
    {
        try { // .... // }
        catch (Exception ex)
        {
            Utils.LastError = ex.Message;
        }
    }
}

Solution

  • If the intended behavior is to hold the last error until it's accessed once, then the way you describe it acting is expected.

    If the intended behavior is to hold onto the last error until another newer error overwrites it, James's point is important to remember. You're clearing the static value once it's accessed, which as Patrick pointed out affects your view in the debugger. The debugger enumerates all properties, because properties aren't intended to have side effects like wiping out the data that backs them.