1

If have a class like this

public static class Globals {
    public static string MyString;

    static Globals() {
        MyString = "example";
    }
}

will MyString always be "example" as long as the app process is running (possibly in background)?

-- EDIT --

Assume that MyString is not changed by the user.

Code
  • 6,041
  • 4
  • 35
  • 75

2 Answers2

2

It is a public, non-final field, so no, there could be all sorts of code that changes its value.

But yes, if you don't change the value, it will stay set. The initializer block is run once when the class itself is loaded, and the field will not somehow magically lose its value. (Even if the class should get unloaded, which I am not sure can ever happen on Android, the field would get re-initialized if the class should get loaded again)

Thilo
  • 257,207
  • 101
  • 511
  • 656
1

Yes, as long as the process exists. Be careful what references you keep to avoid memory leaks. See:

Lifetime of a static variable in Android and Static singleton lifetime in Android.

You can extend Application class for this purpose as well.

Community
  • 1
  • 1
razzledazzle
  • 6,900
  • 4
  • 26
  • 37