C#: Static variables

This entry is part 23 of 71 in the series C#

The word static actually means something that stay constant, fixed or unchanged.

But when it comes to C#, a static variable does not work like a constant variable.

In C#,  A static variable comes into existence before execution of the static constructor. The initial value of a static variable is the default value of the variable’s type.

To understand how static variable works, we can consider the following 2 programs.

With static declaration
using System;

namespace StaticVariable
{
    public class Variable
    {
        public static int i;
        public void Increment()
        {
            i = i+1;
            Console.WriteLine(i);
        }
    }


    public class Program
    {
        static void Main()
        {
            Variable number = new Variable();
            number.Increment();
            Variable number1 = new Variable();
            number1.Increment();
            Variable number2 = new Variable();
            number2.Increment();
            Console.ReadLine();
        }
    }
}

static1

When we run the above code, the output in the console will be 1, 2, 3.

Now consider removing the static declaration in line 7.

Without static declaration
using System;

namespace StaticVariable
{
    public class Variable
    {
        public int i;
        public void Increment()
        {
            i = i+1;
            Console.WriteLine(i);
        }
    }


    public class Program
    {
        static void Main()
        {
            Variable number = new Variable();
            number.Increment();
            Variable number1 = new Variable();
            number1.Increment();
            Variable number2 = new Variable();
            number2.Increment();
            Console.ReadLine();
        }
    }
}

static2

The output from running the above code will be 1,1,1.

So for the first example, each subsequent run of Increment method will increase the integer i.  Whereas in the second example, after removing the static declaration, integer i remains unchanged.

So a static variable value is shared among all instances of that class. And without a static declaration, it will stay constant.

Series Navigation<< C#: Static members
C#: Static classes >>

Leave a comment

Leave a Reply