简体   繁体   中英

Why is static int always 0 when accessed from another class

I have a class with a static int . I want that int , once set, to be accessible anywhere in my program.

public class MyClass
{
   public static int myInt;
   public MyClass()
   {
      myInt = 100;
      new TestClass();
   }

   static void Main(string[] args)
   {
      new MyClass();
   }
}

..but when I try to call it in another class

public class TestClass
{
   public TestClass()
   {
      int testInt = MyClass.myInt;
   }
}

.. testInt is always 0, even when I check in debug mode and see that the static int was successfully set.

What am I doing wrong?

You never instantiate an instance of the class... so the constructor never gets fired.

What you want is a static constructor .. to initialize static members:

public class MyClass {
    public static int myInt;

    static MyClass() { // Static Constructor
        myInt = 100;
    }
}

A static constructor is guaranteed to be fired before any access to an object. Exactly when is undetermined.

Well either as @Simon Whitehead suggested or the best way for this kind of thing is to initialize it when declaring. So you can write it like this:

public static int myInt = 100;

as this is not dependent on anything else, you don't need to wait for constructor.

I can't see any problem in the OP, as the code indeed does the expected job:

在此处输入图片说明

Try adding Console.WriteLine(testInt); in the end of the TestClass constructor. If the code equals the one posted, it should output 100 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM