Static Variables

  • A static variable of a class is shared across all instances of that class.

  • Consider the following class WITHOUT a static member.

public class CountThings
{
    public int ObjectCount { get; private set; } = 0;

    public string Name { get; set; }

    public CountThings()
    {
        ObjectCount++;
    }

    public void PrintObject()
    {
        Console.WriteLine("Name: {0}, Count: {1}", Name, ObjectCount);
    }
}
  • The following code using the above class will produce the following output.

static void Main(string[] args)
{
    var objA = new CountThings() { Name = "A" };
    objA.PrintObject();

    var objB = new CountThings() { Name = "B" };
    objA.PrintObject();
    objB.PrintObject();

    var objC = new CountThings() { Name = "C" };
    objA.PrintObject();
    objB.PrintObject();
    objC.PrintObject();
}
  • However, if the ObjectCount property was marked with the static keyword, while everything else remain the same, executing the same code above will produce the following output instead.

Last updated