Question

When I have a static field in my class:

public static int Counter = 0;

With a static constructor:

static Class() { 
    Counter++; 
}

When I create an object of this class and check Class.Counter it shows me 1 which is correct.

But when I create another object of the same class, Class.Counter remains 1.

Why is that?

Was it helpful?

Solution

Because the static constructor is executed only once.

From C# Specification:

The static constructor for a class executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:

  • An instance of the class is created.
  • Any of the static members of the class are referenced.

OTHER TIPS

That is because you are incrementing your counter in static constructor, and it will be executed just once.

static constructor C# - MSDN

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

You can fix it by incrementing in instance constructor like:

class Class
{
    public static int counter = 0;

    public Class()
    {
        counter++;
    }
}

For thread-safety use Interlocked.Increment(ref counter); instead of counter++

Selman22 has it correct, here is a little more detail:

From MSDN

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is >created or any static members are referenced.

Static constructors have the following properties:

  • A static constructor does not take access modifiers or have parameters.
  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  • A static constructor cannot be called directly.
  • The user has no control on when the static constructor is executed in the program.
  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

Reference url: http://msdn.microsoft.com/en-us/library/k9x6w0hc.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top