Start learning free

LESSON 29 OF 69 · OBJECT-ORIENTED PROGRAMMING

Static Members in C#: A Counter Shared by All Objects

Practice Read the full explanation

TL;DR:

A static field is declared with the static keyword. It belongs to the class, so there is one copy shared by every Dog, and you reach it through the class name: Dog.Count, not rex.Count. A static method works the same way and cannot use this.

You start with:

class Dog {
    public string name;
    public Dog(string name) {
        this.name = name;
    }
}

Your task: count how many Dog objects have been created, with one counter shared by all of them.

  • Add public static int Count = 0; inside Dog.
  • In the constructor, after this.name = name;, add Count++;.
  • The counter starts at 0 before any dog exists, and goes up by exactly 1 for every dog created, whatever its name.
  • The program that is already in the editor creates Rex and Buddy and prints the counter; then it creates Max, prints the counter and Max's name, creates Luna, and prints the counter once more. Do not change those lines.

Expected output:

2
3
Max
4

Read the counter with Dog.Count, not through an object.

class Dog {
    public static int Count = 0;

    public string name;
    public Dog(string name) {
        this.name = name;
        Count++;
    }
}

class Solution {
    public void MainFunction() {
        Dog rex = new Dog("Rex");
        Dog buddy = new Dog("Buddy");
        Console.WriteLine(Dog.Count);
        Dog third = new Dog("Max");
        Console.WriteLine(Dog.Count);
        Console.WriteLine(third.name);
        new Dog("Luna");
        Console.WriteLine(Dog.Count);
    }
}

STEP 1 OF 2
    Ctrl + Enter to check

    C# · OBJECT-ORIENTED PROGRAMMING

    Static Members in C#, explained

    Problem overview

    The lesson starts with a Dog class that has a name field and a constructor. The task is to count how many Dog objects have been created, using one counter shared by all of them. That takes two additions: a public static int Count = 0; field inside Dog, and Count++; at the end of the constructor.

    The program in the editor creates Rex and Buddy and prints the counter, creates Max and prints the counter and Max's name, and finally creates Luna and prints the counter once more. The expected output is:

    2
    3
    Max
    4

    Instance members and static members

    A normal field, such as name, is an instance field. Every Dog object has its own copy, so Rex's name and Buddy's name are independent.

    A static field belongs to the class itself. There is exactly one copy, however many objects exist, even if there are none. Every Dog reads and writes that same copy. This is what a counter of objects needs: a number that no single dog owns.

    Because a static member belongs to the class, you reach it through the class name: Dog.Count. An instance is not involved. Writing rex.Count is rejected by the compiler:

    error CS0176: Member 'Dog.Count' cannot be accessed with an instance reference; qualify it with a type name instead

    Step by step

    1. Declare the field. Inside Dog, add public static int Count = 0;. The keyword static attaches the field to the class. The initializer = 0 runs once, before the field is first used, so the counter reads 0 before any dog exists.
    2. Count in the constructor. Add Count++; after this.name = name;. The constructor runs exactly once for every new Dog(...), whatever the name, so the shared counter goes up by one per dog.

    Inside the class, the constructor can write plain Count. The class name is only needed from outside, as in Dog.Count in the program below.

    The solution in C#

    class Dog {
        public static int Count = 0;
    
        public string name;
        public Dog(string name) {
            this.name = name;
            Count++;
        }
    }
    
    class Solution {
        public void MainFunction() {
            Dog rex = new Dog("Rex");
            Dog buddy = new Dog("Buddy");
            Console.WriteLine(Dog.Count);
            Dog third = new Dog("Max");
            Console.WriteLine(Dog.Count);
            Console.WriteLine(third.name);
            new Dog("Luna");
            Console.WriteLine(Dog.Count);
        }
    }
    

    Reading the program with the counter in mind: after Rex and Buddy the counter is 2, so the first line prints 2. Max makes it 3, and then the program prints Max's name through third.name, which is an instance field and is read through the object. new Dog("Luna") is a statement on its own. The object isn't stored in a variable, but the constructor still runs, so the counter becomes 4.

    The C# details:

    • Static methods work the same way. A static method belongs to the class and is called as Dog.Describe(). Inside it, this doesn't exist, because no particular dog is involved. Using this.name in a static method fails with error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer. A static method can use static fields, such as Count.
    • Instance code can use static members. The constructor is instance code, and it uses Count without any trouble. The reverse is not true: static code can't use instance fields without an object.
    • The static field starts at 0 even without = 0. Fields get their default value, which is 0 for int. Writing = 0 makes the starting value explicit.
    • The result depends on the field being static. If Count were an ordinary field, each dog would get its own counter starting at 0, and the constructor would only raise that private copy to 1. Three dogs would never add up to 3.
    • Console needs using System; in a standalone file.

    A static method beside the field

    A static method can read the shared counter too. Here is Dog with a method that describes it:

    class Dog {
        public static int Count = 0;
        public string name;
        public Dog(string name) {
            this.name = name;
            Count++;
        }
        public static string Describe() {
            return "Dogs: " + Count;
        }
    }
    

    With that class, Console.WriteLine(Dog.Count) prints 0 before any dog exists. After creating two dogs, Dog.Describe() returns "Dogs: 2", and one more new Dog("Luna") raises Dog.Count to 3. No dog was needed to call the method, since it belongs to the class.

    Edge cases and common mistakes

    • Forgetting static. The program in the editor then fails to compile, since Dog.Count needs a static member.
    • Counting somewhere else. Putting Count++ in MainFunction instead of the constructor would count only the dogs that code remembers to count. The constructor counts every dog, however it is created, including new Dog("Luna") with no variable.
    • Resetting in the constructor. A line such as Count = 0; in the constructor would restart the count for every new dog.
    • Reading before the first dog. Dog.Count is 0 then, and no object is needed to read it.
    • Static state is shared everywhere. Any code can change Dog.Count, because it is public. Make the field private and expose a method when you need to protect it.

    Key takeaways

    • static puts a member on the class, not on each object: one copy, shared by all.
    • Reach static members through the class name, as in Dog.Count.
    • A static method has no this.
    • A constructor is the right place to count objects, because it runs for each new one.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free