static member inside constructor in C#

Usually we know in order to access a static variable we need not to create an instance of the class. We can directly do like classname.staticvariable. And in order to access the static variable inside the class we should have a static method.

Now I have a doubt with the following code snippet

public class xyz
{
    private static int a;

    public xyz()
    {
        a++;
    }
}

Will the above code snippet work? If yes why and if no why?

Thanks Prabhanjan

Upvotes: 2

Views: 4403

Answers (8)

Martin Brown
Martin Brown

Reputation: 25310

To quote from the C# documentation on static variables:

Static members are initialized before the static member is accessed for the first time and before the static constructor, if there is one, is called.

For example run the following sample program:

using System;

namespace ScrapCSConsole
{
   class ScrapCSConsole
   {
      public static void Main()
      {
         Console.WriteLine("Create StaticDemo A");
         StaticDemo a = new StaticDemo();
         Console.WriteLine("Create StaticDemo B");
         StaticDemo b = new StaticDemo();
         Console.WriteLine("Done");
      }
   }

   class StaticDemo
   {
      private static int staticDemo1;
      private static int staticDemo2 = 0;
      private static int staticDemo3 = default(int);
      private static int staticDemo4;
      private static int classNumber;

      /// <summary>
      /// Static Constructor
      /// </summary>
      static StaticDemo()
      {
         Console.WriteLine("Static Constructor");
         Console.WriteLine("staticDemo1 {0}", staticDemo1);
         staticDemo4 = (new DateTime(1999, 12, 31)).DayOfYear;
      }

      /// <summary>
      /// Instance Constructor
      /// </summary>    
      public StaticDemo()
      {
         classNumber++;
         Console.WriteLine("classNumber {0}", classNumber);
         Console.WriteLine("staticDemo2 {0}", staticDemo2);
         Console.WriteLine("staticDemo3 {0}", staticDemo3);
         Console.WriteLine("staticDemo4 {0}", staticDemo4);                  
      }      
   }
}

And you get the following output:

Create StaticDemo A
Static Constructor 
staticDemo1 0
classNumber 1
staticDemo2 0
staticDemo3 0
staticDemo4 365
Create StaticDemo B
classNumber 2
staticDemo2 0
staticDemo3 0
staticDemo4 365
Done

There are some interesting things to note here:

  1. The line 'Console.WriteLine("Create StaticDemo A")' gets called before StaticDemo's static constructor.
  2. The line 'Console.WriteLine("Static Constructor")' only gets called once.
  3. The line 'Console.WriteLine("staticDemo1 {0}", staticDemo1)' works even though staticDemo1 has never been explicitly initialized.
  4. staticDemo1, staticDemo2 and staticDemo 3 all start out as 0 in value.

Finally as a sub note you need to be careful if you are creating the objects on multiple threads. This is because classNumber++ is not an atomic operation. It counts as two seperate operations one read and one write. As such two seperate threads can both read the variable before either one of them writes out the incremented value. To avoid this situation use this line instead:

System.Threading.Interlocked.Increment(ref classNumber);

Upvotes: 2

Mohammadreza
Mohammadreza

Reputation: 3229

It doesn't work if you want access to static var, you must decalar it public and Constructor method doesn't run, because constructors runs when you use initialize a class and create an object.

Upvotes: 0

Hossein Narimani Rad
Hossein Narimani Rad

Reputation: 32481

It works.

Imagine you want to know how many instance of a class has been created. So in this case you can use

xyz.a 

Also to monitor number of lived instances you can create a destructor and use a--.

Upvotes: 2

D J
D J

Reputation: 7028

Yes it will work. You can refer static member in instance members but can not refer instance members in static members because they need instance to work and static does not.

Upvotes: 0

daryal
daryal

Reputation: 14919

the following assumption is not correct;

in order to access the static variable inside the class we should have a static method.

The code you have provided works since you do not need a static method.

try the following and you will see it also works;

public class xyz
{
    private static int a;

    public void A()
    {
        a++;
    }
}

Upvotes: 0

mihirj
mihirj

Reputation: 1219

The above snippet will perfectly work fine. Such kind of code is written to count the number of live instances present for a class.

public class xyz
{
    private static int a;

    public xyz()
    {
        a++;
    }

    public static int A
    {
        get { return a;}
    }
}

Print number of live instances as:

Console.WriteLine(obj.A);

Upvotes: 0

Martin Baulig
Martin Baulig

Reputation: 3010

It is perfectly fine to access a static member from an instance method.

The static variable a has a default value of 0 and your code increments it each time you create an instance of the class.

Upvotes: 1

JMan
JMan

Reputation: 2629

Yes it will. The int will have a default value of 0. Everytime the constructor is called you will increase your static variable.

Upvotes: 4

Related Questions