user3138018
user3138018

Reputation: 11

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?

Upvotes: 1

Views: 466

Answers (3)

horgh
horgh

Reputation: 18534

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

enter image description here

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

Upvotes: 1

TheVillageIdiot
TheVillageIdiot

Reputation: 40507

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.

Upvotes: 2

Simon Whitehead
Simon Whitehead

Reputation: 65079

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.

Upvotes: 2

Related Questions