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
- Declare the field. Inside
Dog, addpublic static int Count = 0;. The keywordstaticattaches the field to the class. The initializer= 0runs once, before the field is first used, so the counter reads 0 before any dog exists. - Count in the constructor. Add
Count++;afterthis.name = name;. The constructor runs exactly once for everynew 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
staticmethod belongs to the class and is called asDog.Describe(). Inside it,thisdoesn't exist, because no particular dog is involved. Usingthis.namein a static method fails witherror CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer. A static method can use static fields, such asCount. - Instance code can use static members. The constructor is instance code, and it uses
Countwithout 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 forint. Writing= 0makes the starting value explicit. - The result depends on the field being static. If
Countwere 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. Consoleneedsusing 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, sinceDog.Countneeds a static member. - Counting somewhere else. Putting
Count++inMainFunctioninstead of the constructor would count only the dogs that code remembers to count. The constructor counts every dog, however it is created, includingnew 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.Countis 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 fieldprivateand expose a method when you need to protect it.
Key takeaways
staticputs 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.
